错误:与“operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}”和“void”不匹配)

问题描述 投票:0回答:1

这是我的代码(我只写了本质),我得到了这个:

错误:与“运算符<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘void’)

不匹配”
class Mobil {
public:
void print() const; 
int  getNumber() const;
double getData() const;
friend ostream& operator <<(ostream&, const Mobil&);
};

ostream& operator<<(ostream& out, const Mobil& mobil) {
    out << mobil.print() << endl;
    return out;
}

有什么问题吗?

c++ c++11
1个回答
5
投票

问题出在这一行:

out << mobil.print() << endl;
。您的
print()
方法不会返回任何内容(是
void
的类型),因此无法将其发送到
ostream

要解决此问题,您的

print()
方法应该以
ostream
支持的类型之一返回您想要打印输出的任何内容,您可以在 C++ 参考中找到该类型。

© www.soinside.com 2019 - 2024. All rights reserved.