简体   繁体   English

在C ++中重载运算符时如何获取THIS

[英]How to get THIS when overloading operator in C++

I'm a student learning c++. 我是一名学习c ++的学生。 today, I was making a operator overload function to use it in 'cout'. 今天,我正在制作一个运算符重载函数以在'cout'中使用它。 following is a class that contains name, coordinates, etc. 以下是包含名称,坐标等的类。

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;
}

However, this code isn't working because of 'THIS' keyword that I was expecting it points to the object. 但是,由于我希望'THIS'关键字指向该对象,因此该代码无法正常工作。 I want to show the object's name and distance value. 我想显示对象的名称和距离值。 How can I solve it? 我该如何解决? I think it is similar with Java's toString method so that it will be able to get THIS. 我认为它与Java的toString方法类似,因此它将能够获取此信息。

Thanks in advance for your answer and sorry for poor english. 在此先感谢您的回答,对不起,英语不好。 If you don't understand my question don't hesitate to make a comment. 如果您不明白我的问题,请随时发表评论。

this is available only in member functions, but your operator<< is not a class member (declaring it as friend does not make it a member). this仅在成员函数中可用,但是您的operator<<不是类成员(将其声明为friend不会使其成为成员)。 It is a global function, as it should be. 它应该是全局函数。 In a global function, just use the arguments you are passing in: 在全局函数中,只需使用传入的参数即可:

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

Also note os replaced cout in the code above. 另请注意,在上面的代码中os替换了cout Using cout was an error - the output operator should output to the provided stream, not to cout always. 使用cout是一个错误-输出运算符应输出到提供的流,而不是始终输出cout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM