如何使用结构传递文件对象
how to pass file object using structure?
我在使用结构传递文件对象时遇到一个问题,代码是
#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。请告诉我我错在哪里?
您需要初始化
成员初始值设定项列表中的引用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
。
不能重新拔插引用。它们必须初始化,并且没有引用的"默认"值。因此,您需要使用对文件流对象的引用构造abc
的实例:
struct abc
{
std::ofstream &t;
};
然后
abc myabc = {str};
或者给abc
一个构造函数并使用构造函数初始化列表:
struct abc
{
abc(std::ofstream& o) : t(o) {}
std::ofstream &t;
};
abc myabc(str);
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在h文件中包含.o对象文件
- 如何使用单独文件中的派生类访问友元函数对象
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 使用逗号解析文件对象?
- 使用 CIN COUT 显示垃圾值的文件对象?
- 如何确保我的"ifstream"文件对象指向的文件内容已更新?
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- pyQt5 将文件对象传递给 QWebEngineView
- 从文件对象的当前位置删除字符
- 使用相同的文件对象按顺序写入和读取文件
- 将 ETW 文件对象与 DiskIO 事件相关联
- 如何在构建时将 JSON 文件/对象包含在C++中
- 如何使用运算符<<通过 << 将文件对象馈送到我的类?
- 确定两个文件路径引用同一文件对象的最佳方法是什么
- 文件映射对象和文件对象可以互换使用吗
- 如何判断给定点是否在STereoLithography(.stl)文件对象c++内
- 如何使用Windows Portable Devices C++API获取MTP设备公开的文件夹中的所有文件(对象)的列
- 如何使用结构传递文件对象
- 文件对象->文件名不返回文件的完整路径