error: invalid operands of types ‘std::ofstream*‘ {aka ‘std::basic_ofstream<char>*‘} and ‘const char

1)代码

#include <iostream>
#include <vector>
#include <fstream>
class Point {
public:
    int x;
    std::string b;
    std::ofstream *of;
    int y;
};
int main() {
    std::vector<Point> points;
    std::ofstream outfile;
    outfile.open("tmp.txt"); 
    Point pt1 = {1,"b1", &outfile, 2};
    std::ofstream outfile2;
    Point pt2 = {3,"b2", &outfile2, 4};
    points.push_back(pt1);
    points.push_back(pt2); 
    std::cout<< points[0].x << ", " << points[0].b << ", "<< points[0].y << std::endl;
    std::cout<< points[1].x << ", " << points[1].b << ", "<< points[1].y << std::endl;
    points[0].of << "hello world\n";
 
    return 0;
}

2)报错

a2.vector.cpp: In function 'int main()':
a2.vector.cpp:22:18: error: invalid operands of types 'std::ofstream*' {aka 'std::basic_ofstream<char>*'} and 'const char [13]' to binary 'operator<<'
     points[0].of << "hello world\n";
3)

错误分析

points[0].of是个引用,因为前面 std::ofstream *of;是定义是的一个指针,

所以要加*

4)

points[0].of << "hello world\n";

改成

points[0].*of << "hello world\n";

仍然报错

a2.vector.cpp: In function 'int main()':
a2.vector.cpp:22:16: error: 'of' was not declared in this scope
     points[0].*of << "hello world\n";
                ^~
a2.vector.cpp:22:16: note: suggested alternative: 'feof'
     points[0].*of << "hello world\n";
 

5)

    points[0].of << "hello world\n";

改成

    *points[0].of << "hello world\n";

其实应该是    *(points[0].of) << "hello world\n";

就对了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值