开发者

Simple vector program error

开发者_JAVA技巧

Hi iam new to c++ and iam trying out this vector program and i am getting the following error: error: conversion from test*' to non-scalar typetest' requested|

Here is the code

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

class test{

    string s;
    vector <string> v;
    public:
    void read(){
        ifstream in ("c://test.txt");
        while(getline(in,s))
        {
             v.push_back(s);
        }
        for(int i=0;i<v.size();i++)
        {
        cout<<v[i]<<"\n";
        }
    }

};
int main()
{
    cout<<"Opening the file to read and displaying on the screen"<<endl;
    test t=new test();
    t.read();

}


new is used to dynamically allocate memory. You don't need to do that, so just do:

test t; // create an instance of test with automatic storage
t.read(); // invoke a method

The error is because the type of new test() is a test*, a pointer to a (newly created) test. You can't assign a test* to a test.


The pointer version, for what it's worth, would have been:

test* t = new test();
t->read(); // the arrow is short for (*test).
delete t; // don't forget to clean up!

However, it's bad style to do raw memory allocation like that. You'd use something called a smart pointer to make sure it gets deleted automatically, instead. The standard library has one in the header <memory>, called auto_ptr, that would suffice:

std::auto_ptr<test> t(new test()); // put a new test into a pointer wrapper
t->read(); // treat it like a normal pointer
// nothing else to worry about, will be deleted automatically

However, all this isn't needed for you, in this case. Always prefer automatic (stack) allocation over dynamic allocation.


Change

test t=new test();
t.read();

to

test *t=new test();
t->read();

t should be a pointer to type test. And to access a class member using a pointer we use the -> operator. Also its a good practice to delete any dynamically allocated objects as:

delete t;


new test() will return a pointer to a t so you either want to use pointer throuought or create t on the stack

Code using pointers

test *t=new test();
t->read();    // note needs -> rather than .
delete t;   // as declared n the heap you must delete

or usually better do all on the stack

test t;
t.read();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜