我在使用结构传递文件对象时遇到一个问题,代码是
#include <iostream>
#include<fstream>
using namespace std;
typedef struct abc
{
ofstream &t;
}stabc;
class dc
{
public:
static void fun(stabc *ad);
static stabc ab;
};
int main()
{
ofstream str;
str.open("hello.csv",ios::app);
str<<"hellllooo"<<endl;
dc d;
d.ab.t=str;
dc::fun(&d.ab);
cout << "Hello world!" << endl;
return 0;
}
void dc::fun(stabc *ad)
{
ofstream& st=ad->t;
st<<"kikiki"<<endl;
}
它给出未初始化的引用成员 abc::t。请告诉我哪里错了?
最佳答案
您需要在 member initializer list 中初始化引用t
.
引用是一种特殊的构造,需要在创建时进行初始化。由于您没有初始化成员引用,因此编译器会发出诊断信息。
成员引用必须在成员初始化器列表中初始化。
#include <iostream>
#include <fstream>
using namespace std;
struct stabc
{
ofstream &t;
stabc(ofstream &obj):t(obj){}
};
int main()
{
ofstream obj2;
stabc obj(obj2);
return 0;
}
另请注意,在 C++ 中(与 C 不同)您无需typedef
结构即可在没有关键字 struct
的情况下使用它。您可以简单地使用结构名称,而无需在 struct
之前添加。
关于c++ - 如何使用结构传递文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14558007/