重载cout时未定义引用
undefined reference while overloading cout
我已经使用dev c++定义了一个点类。然后我试着让cout为这门课超载。在不使用它的时候,我不会出错。但当我主要使用它时,它会给我这个错误:
[Linker error] C:UsersMohammadDesktopAP-New folderpoint/main.cpp:12: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Point const&)'
//点.h
class Point{
private:
double x;
double y;
double z;
public:
//constructors:
Point()
{
x=0;
y=0;
z=0;
}
Point(double xx,double yy,double zz){x=xx; y=yy; z=zz;}
//get:
double get_x(){return x;}
double get_y(){return y;}
double get_z(){return z;}
//set:
void set_point(double xx, double yy, double zz){x=xx; y=yy; z=zz;}
friend ostream &operator<<(ostream&,Point&);
};
//point.cpp
ostream &operator<<(ostream &out,Point &p){
out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")n";
return out;
}
//main.cpp
#include <iostream>
#include "point.h"
using namespace std;
int main(){
Point O;
cout<<"O"<<O;
cin.get();
return 0;
}
这是因为在声明和定义运算符时没有将Point
设为const
。更改您的声明如下:
friend ostream &operator<<(ostream&, const Point&);
同时在定义中添加const
:
ostream &operator<<(ostream &out, const Point &p){
out<<"("<<p.x<<", "<<p.y<<", "<<p.z<<")n";
return out;
}
请注意,您发布的代码不需要Point&
的const
。其他一些代码使编译器或IDE相信引用了具有const
的运算符。例如,使用这样的运算符需要const
cout << Point(1.2, 3.4, 5.6) << endl;
(演示)
由于上面的代码片段创建了一个临时对象,因此C++标准禁止将对它的引用作为非常数传递。
与此问题没有直接关系,但您可能还想标记单个坐标const
的三个getter:
double get_x() const {return x;}
double get_y() const {return y;}
double get_z() const {return z;}
这将允许您使用getter访问标记为const
的对象上的坐标。
相关文章:
- 编译C++时未定义的引用
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 对 Scalar ::Scalar() 的未定义引用
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 对复制 CTOR 和 CTOR 的未定义引用
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 右值引用未定义的行为
- 对"vtable for DigitalClock"的未定义引用 - 未定义对"DigitalClock::staticMetaObject"的引用 - Qt
- 函数类型到函数类型的引用:未定义的引用
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确
- 从c++调用Fortran子程序,链接时引用未定义
- 枚举引用未定义,但位于包含的头文件中