一、同名隐藏
儿子就是比老子强一点,儿子继承的东西都能用,父亲就是没有儿子的特殊技能
#include <iostream>
using namespace std;
class Father{
public:
Father(){}
Father(const Father& f){
cout << "Father copy" << endl;
}
Father& operator=(const Father& f){
cout << "=" << endl;
}
void Func(){
cout << "Father ::Func " << endl;
}
void Func(int n){
cout << "Father::Func(n)" << endl;
}
};
class Son:public Father{
public:
using Father::Func;
void Func(){
cout << "Son::Func " << endl;
}
void Test(){
Father::Func();
Father::Func(1);
}
};
void Test1(Father* f){
f->Func();
}
void Test2(Father& f){
f.Func();
}
int main(){
//Son s;
//s.Func();
//s.Test();
//s.Func(1);
Son* s = new Son;
s->Father::Func();
s->Test();
s->Func(1);
delete s;
s =NULL;
// Father f;
// f = *s;
//Son s1 = f;
Son s1;
Father f = s1; //对象
f = s1;
f.Func();
Father* pf = &s1;//指针
pf->Func();
Father& f1 = s1;//引用
f1.Func();
Test1(&s1);
Test2(s1);
}
二、
基类已有的函数,子类也有同名函数,那么赋值调用时只会调用基类同名函数
如果想通过传参用自己的函数那么就必须在基类把同名汉函数改成虚拟的
#include <iostream>
using namespace std;
class A{
public:
virtual void Print(){
cout << "A" << endl;
}
};
class B:public A{
public:
void Print(){
cout << "B" << endl;
}
};
class C:public A{
public:
void Print(){
cout << "C" << endl;
}
};
void Print(A& a){
a.Print();
}
int main (){
B b;
C c;
A& ra = b;
ra.Print();
A* fa = &b;
fa->Print();
Print(b);
Print(c);
}