详解C++之函数重载

2020-06-15 14:00:02于丽

函数重载本质

c++中通过函数名和函数确定一个函数
所以相同的函数名,不同参数也是可以的
不同于c语言,c语言没有函数重载,函数的本质地址就是函数名
函数重载发生在同一个作用域内

类中的重载

构造函数重载
普通成员函数重载
静态成员函数重载

全局函数、静态成员函数、普通成员函数可以发生重载吗?

本质就是函数名和函数参数不同,并且发生在同一个作用域
静态函数和普通成员函数是可以的
全局函数作用域在全局作用域,所以不可以

问题1:当父类的成员函数和子类的成员函数相等,会发生重载吗?

本质还是上面说的,因为父类和子类的作用域不在同一个

看一段代码

 #include <iostream>

class father{
public:
 father() {
  std::cout << "father()" << std::endl;
 }
 void print() {
  std::cout << "father print" << std::endl;
 }
};

class child : public father{
public:
 child() {
  std::cout << "child()" << std::endl;
 }
 void print(int a) {
  std::cout << "child print = " << a << std::endl;
 }
};

int main(){
 father* father_test = new father();
 father_test->print(); //打印father print

 child* child_test2 = new child();
 child_test2->print(); //编译错误no matching function for call to 'child::print()'
      
 return 0;
}

由打印输出可得第一个打印属于father正常输出,没问题,第二个打印是编译错误,我们其实想访问的是父类的print,但是由于子类定义了print,那么在子类的作用域中,print这个函数现在只存在一个,那就是void print(int a),如果想调用父类的就要显示指定child_test2->father::print();

问题2,子类可以重写父类的函数吗,或者说定义相同的?

看代码

#include <iostream>

class father{
public:
 father() {
  std::cout << "father()" << std::endl;
 }
 void print() {
  std::cout << "father print" << std::endl;
 }
};

class child : public father{
public:
 child() {
  std::cout << "child()" << std::endl;
 }
 void print() {
  std::cout << "child print" << std::endl;
 }
};

int main(){
 father* father_test = new father();
 father_test->print(); //打印father print

 child* child_test2 = new child();
 child_test2->print(); //child print

 return 0;
}

可见是可以定义相同的函数,并重写的

问题3,当全局运算符重载遇上类中的运算符重载,优先级是什么

 #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 father& e1, const father& 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;
}