c++ - 简单 vector 程序错误

标签 c++ vector instantiation

嗨,我是 C++ 的新手,我正在尝试这个 vector 程序,我收到以下错误: 错误:请求从 test*' 转换为非标量类型test'|

这是代码

#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用于动态分配内存。您不需要这样做,所以只需这样做:

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

错误是因为new test()的类型是 test* , 指向(新创建的)test 的指针.您不能分配 test*test .


就其值(value)而言,指针版本应该是:

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

但是,这样进行原始内存分配是一种糟糕的风格。相反,您会使用一种称为智能指针的东西来确保它被自动删除。标准库在标题中有一个 <memory> , 称为 auto_ptr ,这就足够了:

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

但是,在这种情况下,您不需要所有这些。始终喜欢自动(堆栈)分配而不是动态分配。

关于c++ - 简单 vector 程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2535783/

相关文章:

c++ - Qt 4.8.5 理解 QMessagebox .exec() 和 .show()

c++ - C++推导的返回类型在定义之前不能使用

C++ std::vector 搜索值

c# - 在构造函数中或在类的顶部创建一个对象

c++ - 模板推导趣事,c++

ios - 如何创建其基类具有 Storyboard 的子类 View Controller ?

c++ - 尝试构建 Skia 时缺少头文件

c# - 如何调试DLL里面的代码

c++ - 如何将具有一定数量单词的 vector<string> 的输出读取到一行?

c++ - 析构函数调用两次