简体   繁体   English

类内的重载>>运算符

[英]overloading >> operator inside class

What is the difference between the following ways to oveload the >> operator? 以下几种>>操作符之间的区别是什么?

class A {
public:
    istream& operator>>(istream& is) { return is >> x; };
private:
    int x;
};

class B {
public:
    friend istream& operator>>(istream& is, B b) { return is >> b.y; };
private:
    int y;
};

I can't use std::cin >> a but I can do std::cin >> b . 我不能使用std::cin >> a但是我可以使用std::cin >> b

Isn't the first way a legit way to overload? 第一种方法不是合法的过载方法吗?

When you do an in-member overload of an operator, then the left-hand-side of that operator is an instance of the class. 当您对运算符进行成员内重载时,该运算符的左侧是该类的实例。

For example, with your A class: 例如,对于您的A类:

A a;
a >> std::cin;  // Calls a.operator>>(std::cin)

When you declare the friend function for class B , it's not a member function but a non-member function. 当您为类B声明friend函数时,它不是成员函数,而是非成员函数。 It's basically the same as doing 基本上和做的一样

class B {
public:
    friend istream& operator>>(istream& is, B b);  // Just declare the function
private:
    int y;
};

// Here's the function definition
istream& operator>>(istream& is, B b) { return is >> b.y; };

With this function, the left-hand-side is passed as the first argument, and the right-hand-side is passed as the second argument. 使用此功能,左侧作为第一个参数传递,右侧作为第二个参数传递。

Which means 意思是

B b;
std::cin >> b;  // Equal to operator>>(std::cin, b)

不,第一个不是“合法”,因为通常您希望>>istream作为其左侧参数,但是您的成员函数将A作为其左侧参数(如this ),意味着您不能调用std::cin >> a ,但是可以调用a >> std::cin ,这没有什么意义。

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

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