如何在C++中重载operator时得到这个

Lik*_*oed 0 c++

我是一名学习c ++的学生.今天,我正在制作一个运算符重载函数,以便在'cout'中使用它.以下是包含名称,坐标等的类.

class Custom {
public:
    string name;
    int x;
    int y;

    Custom(string _name, int x, int y):name(_name){
        this->x = x;
        this->y = y;
    }
    int getDis() const {
        return static_cast<int>(sqrt(x*x+y*y));
    }
    friend ostream& operator << (ostream& os, const Custom& other);
};

ostream& operator << (ostream& os, const Custom& other){
    cout << this->name << " : " << getDis() << endl;; // error
    return os;
}
Run Code Online (Sandbox Code Playgroud)

但是,由于我希望它指向对象的'THIS'关键字,此代码无效.我想显示对象的名称和距离值.我该如何解决?我认为它与Java的toString方法类似,因此它可以获得这个.

提前感谢您的回答,并抱歉英语不好.如果您不理解我的问题,请不要犹豫,发表评论.

Woj*_*wka 6

this仅在成员函数中可用,但您operator<<不是类成员(声明它friend不会使其成为成员).它应该是一个全球性的功能.在全局函数中,只需使用您传入的参数:

ostream& operator << (ostream& os, const Custom& other)
{
    os << other.name << " : " << other.getDis() << endl;
    return os;
}
Run Code Online (Sandbox Code Playgroud)

另请注意在上面的代码中os替换cout.使用cout是一个错误 - 输出操作符应输出到提供的流,而不是cout始终.