重载cout时未定义引用

undefined reference while overloading cout

本文关键字:引用 未定义 cout 重载      更新时间:2023-10-16

我已经使用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的对象上的坐标。