输出为void print(const father& e)类中的运算符重载优先级大于全局
当复制兼容遇上全局重载呢?
#include <iostream>
class child;
class father{
public:
father() {
std::cout << "father()" << std::endl;
}
bool operator==(const father& e) {
std::cout << "void print(const father& e)" << std::endl;
}
};
bool operator==(const child& e1, const child& e2) {
std::cout << "void print(const child& e1, const child& e2)" << std::endl;
}
class child : public father{
public:
child() {
std::cout << "child()" << std::endl;
}
};
int main(){
child child1_test;
child child2_test;
child1_test==child2_test;
return 0;
}
打印:"void print(const child& e1, const child& e2)"
仅仅变化了,全局的函数参数类型,正常来说类中和全局的==都是可以的,但是当类中的需要一个默认的转换,子类到父类,全局的是直接类型就对的上的,编译器就优先使用全局的
说到运算符重载,我们现在定义函数实现类的功能有三种选择:成员函数,全局函数,全局函数+友元函数
1.看是否需要虚函数,如果需要虚函数,那么肯定是类的成员函数
2.看是否定义的是<<或者>>运算符,我们都知道打印输出是全局<<,但是为什么呢,看一下实际的原型针对String而言ostream& operator<<(ostream& output, const String& string)我们使用的时候就是 std::cout << "haha";
如果定义为类中的就是ostream& operator<<(ostream& output)使用起来就是 "haha"<<"std::cout"看出差别了吧,如果定义在类中使用起来就很别扭,继续上面的结果,如果是<<或者>>运算符,然后如果需要访问private域,那么就把全局函数变为类对应的友元函数
3.当需要对左边的参数进行类型转换,需要定义全局函数,因为类中操作符函数,左边的就是类本身,如果需要访问private域,那么就把全局函数变为类对应的友元函数
4.其他情况为类的成员函数
以上就是详解C++之函数重载的详细内容,更多关于c++之函数重载的资料请关注易采站长站其它相关文章!










