C++中的重载<<出错
Error Overloading << in C++
,所以我试图超载&lt;&lt;操作员。我在标题文件中定义了如下:
&operator<<(std::ostream &o, const gVector3 &v)
我已经在CPP文件中定义了它:
std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){
return o << "The vector elements are" << v[0] << v[1] << v[2];
}
我会收到以下错误消息。有人知道为什么吗?
C:QtToolsQtCreatorbinHomework1gVector3.cpp:112: error: 'std::ostream& gVector3::operator<<(std::ostream&,
const gVector3&)' must take exactly one argument
std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){
您的帮助非常感谢! ^
您已将声明放在类定义中,对于编译器而言,这意味着它是成员函数 - 运算符,因为类成员只能采用一个参数。另一个参数是您要调用的对象。更轻松理解的示例:
struct Foo {
void operator<<(int) { }
};
int main()
{
Foo f;
f << 5;
// can be also called like this:
f.operator<<(5);
}
您需要的是friend
指示符,以告诉编译器您要声明一个非会员:
friend std::ostream& operator<<(std::ostream &o, const gVector3 &v)
这次是非会员的另一个示例:
struct Foo {
friend void operator<<(Foo, int) { }
};
int main()
{
Foo f;
f << 5;
// this time, it can be called like this:
operator<<(f, 5);
}
这是假设操作员需要访问gVector3
的私人数据。如果没有,请删除friend
并在课堂外声明。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 呼叫运营商<<临时
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为x86而非x64编译时出错
- <<操作员在下面的行中工作
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了