gpt4 book ai didi

c++ - 简单 vector 程序错误

转载 作者:行者123 更新时间:2023-11-30 01:31:52 25 4
gpt4 key购买 nike

嗨,我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com