在c ++中会发生什么,如果两个对象都重载运算符<<?一个<< b

Eng*_*nık 4 c++ operator-overloading

我想到了

cout << "Hello world" 
Run Code Online (Sandbox Code Playgroud)

cout对象有一个运算符重载,所以我们可以传递stringscout对象成员函数.

但是在一些示例代码中,我看到了一个在其中定义了运算符重载的类.

class GenericPlayer : public Hand
{
    ..
    friend ostream& operator <<(ostream& os, const GenericPlayer& aGenericPlayer);
    ..
};

...
cout << aGenericPlayer << endl;
...
Run Code Online (Sandbox Code Playgroud)

即使不是这样,如果什么都coutaGenericPlayer超载operator<<

jua*_*nza 8

即使不是,如果cout和aGenericPlayer都重载运算符<<?

std::cout是一个std::ostream对象,所以任何人std::ostream& operator<<(std::ostream, SomeType)都可以使用std::cout.但重点是运算符的第二个参数是不同的,因此重载是不同的.第一个"字符串"就像是

std::ostream& operator<<(std::ostream&, const char*);
Run Code Online (Sandbox Code Playgroud)

第二个

std::ostream& operator <<(std::ostream& os, const GenericPlayer& aGenericPlayer); 
Run Code Online (Sandbox Code Playgroud)

因此,它们是不同的运算符重载,并且没有歧义.