父子类间的冲突

父子类中同名成员的规则
子类可以定义父类中的同名成员
子类中的成员将隐藏父类中的同名成员
父类的同名成员依然存在于子类中
通过作用域分辨符(::)访问父类中的同名成员
例子:

#include <iostream>
#include <string>
using namespace std;
class Parent
{
  public:
  int mi;
  Parent()
  {
    cout<<"Parent() : "<<"&mi is "<<&mi<<endl;
  }
};
class Child : public Parent
{
   public:
   int mi;
   Child()
   {
     cout<<"Child() : "<<"&mi is "<<&mi<<endl;
   }
};
int main()
{
  Child c;
  
  c.mi = 10;
  
  c.Parent::mi = 20;
  
  cout<<"the Child mi is"<<c.mi<<endl;
  cout<<"the Child &mi is"<<&c.mi<<endl;
  
  cout<<"the Parent mi is"<<c.Parent::mi<<endl;
  cout<<"the Parent &mi is"<<&c.Parent::mi<<endl;
  
  return 0;
}

结果:

sice@sice:~$ ./a.out 
Parent() : &mi is 0xbff7c968
Child() : &mi is 0xbff7c96c
the Child mi is10
the Child &mi is0xbff7c96c
the Parent mi is20
the Parent &mi is0xbff7c968

可以看出父子类的同名成员可以通过作用域分辨符来区别,用作用域分辨符来访问父类中的同名成员,默认情况会访问子类的同名成员变量,也就是mi虽然有两个同名,但是它们在两个不同的作用域所以可以通过作用域分辨符来区别.

我们之前说过类中的成员函数可以进行重载,重载函数的本质为多个不同的函数,函数名和参数列表时唯一标识,函数重载必须发生在同一作用域中,那么父子间的同名函数也是不可以算是重载的,需要用作用域分辨符来辨别,函数体内访问的变量是本作用域中的变量,
例子:

#include <iostream>
#include <string>
using namespace std;
class Parent
{
  public:
  int mi;
  Parent()
  {
    cout<<"Parent() : "<<"&mi is "<<&mi<<endl;
  }
  void add(int a,int b)
  {
     mi += a + b;
  }
  void add(int c)
  {
     mi += c;
  }
};
class Child : public Parent
{
   public:
   int mi;
   Child()
   {
     cout<<"Child() : "<<"&mi is "<<&mi<<endl;
   }
   void add(int a,int b,int c)
   {
     mi+= a + b + c;
   }
};
int main()
{
  Child c;
  
  c.mi = 10;
  
  c.Parent::mi = 20;
  
  cout<<"the Child mi is"<<c.mi<<endl;
  cout<<"the Parent mi is"<<c.Parent::mi<<endl;
  
  c.add(1,2,3);
  cout<<"the Child mi is"<<c.mi<<endl;
  
  c.Parent::add(1);
  c.Parent::add(1,1);
  
   cout<<"the Parent mi is"<<c.Parent::mi<<endl;
  return 0;
}

结果:

sice@sice:~$ ./a.out 
Parent() : &mi is 0xbfae6c48
Child() : &mi is 0xbfae6c4c
the Child mi is10
the Parent mi is20
the Child mi is16
the Parent mi is23

可以看出子类中的函数将隐藏父类的同名函数,无法重载父类的成员函数,因为不在同一片作用域,使用作用域分辨符访问父类中的同名函数,当然子类也可以定义和父类中完全相同的成员函数,当子类没有和父类同名函数时,使用对象.函数名访问父类成员函数

发布了83 篇原创文章 · 获赞 3 · 访问量 1269

猜你喜欢

转载自blog.csdn.net/qq_41936794/article/details/104856830