一、子类中是否可以定义与父类中的同名函数,如果可以这么区分?
实例分析:同名成员变量分析
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
};
class Child : public Parent
{
public:
int mi;
};
int main()
{
Child c;
c.mi = 100; // mi 究竟是子类自定义的,还是从父类继承得到的?
return 0;
}
结论:
- 子类可以定义父类中的同名成员
- 子类中的成员将隐藏父类中的同名成员,但不会销毁
- 父类中的同名成员依然存在于子类中
- 通过作用域分辨符(::)访问父类中的同名成员
访问父类中的同名成员
Child c;
c.mi-100;子类中的mi
c.Parent::mi=1000;父类中的mi
实例分析2:同名成员变量的深度分析
#include <iostream>
#include <string>
using namespace std;
namespace A
{
int g_i = 0;
}
namespace B
{
int g_i = 1;
}
class Parent
{
public:
int mi;
Parent()
{
cout << "Parent() : " << "&mi = " << &mi << endl;
}
};
class Child : public Parent
{
public:
int mi;
Child()
{
cout << "Child() : " << "&mi = " << &mi << endl;
}
};
int main()
{
Child c;
c.mi = 100;
c.Parent::mi = 1000;
cout << "&c.mi = " << &c.mi << endl;
cout << "c.mi = " << c.mi << endl;
cout << "&c.Parent::mi = " << &c.Parent::mi << endl;
cout << "c.Parent::mi = " << c.Parent::mi << endl;
return 0;
}
Parent() : &mi = 0x6ffe00
Child() : &mi = 0x6ffe04
&c.mi = 0x6ffe04
c.mi = 100
&c.Parent::mi = 0x6ffe00
c.Parent::mi = 1000
二、再论重载
- 类中的成员函数可以进行重载
- 重载函数的本质为多个不同的函数
- 函数名和参数列表是唯一的标识
- 函数重载必须发生在用一个作用域中
问题:子类中定义的函数是否能重载父类中的同名函数
实例分析:父子间的函数重载
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
void add(int v)
{
mi += v;
}
void add(int a, int b)
{
mi += (a + b);
}
};
class Child : public Parent
{
public:
int mi;
void add(int v)
{
mi += v;
}
void add(int a, int b)
{
mi += (a + b);
}
void add(int x, int y, int z)
{
mi += (x + y + z);
}
};
int main()
{
Child c;
c.mi = 100;
c.Parent::mi = 1000;
cout << "c.mi = " << c.mi << endl;
cout << "c.Parent::mi = " << c.Parent::mi << endl;
c.add(1);
c.add(2, 3);
c.add(4, 5, 6);
cout << "c.mi = " << c.mi << endl;
cout << "c.Parent::mi = " << c.Parent::mi << endl;
return 0;
}
c.mi = 100
c.Parent::mi = 1000
c.mi = 121
c.Parent::mi = 1000
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
void add(int v)
{
mi += v;
}
void add(int a, int b)
{
mi += (a + b);
}
};
class Child : public Parent
{
public:
int mi;
//与前文代码的区别是这里没有
/* void add(int v)
{
mi += v;
}
void add(int a, int b)
{
mi += (a + b);
}
*/
void add(int x, int y, int z)
{
mi += (x + y + z);
}
};
int main()
{
Child c;
c.mi = 100;
c.Parent::mi = 1000;
cout << "c.mi = " << c.mi << endl;
cout << "c.Parent::mi = " << c.Parent::mi << endl;
c.add(1);
c.add(2, 3);
c.add(4, 5, 6);
cout << "c.mi = " << c.mi << endl;
cout << "c.Parent::mi = " << c.Parent::mi << endl;
return 0;
}
编译报错:
45[Error] no matching function for call to 'Child::add(int)'
46 [Error] no matching function for call to 'Child::add(int, int)'
子类中的void add(int x, int y, int z)把父类中的两个add覆盖了,子类中的add与父类中的add不构成重载,它们不在用一个作用域中。
结论:
- 子类中的函数将隐藏父类中的同名函数
- 子类无法重载父类中的成员函数,不构成重载关系
- 使用作用域分辨符访问父类中的同名函数
- 子类可以定义父类中完全相同的成员函数