转载:https://blog.csdn.net/gogogo_sky/article/details/72860426
简单示例:
重新定义
#include<iostream>
using namespace std;
class a {
public:
void fun() {
cout << "a";
}
};
class b:public a {
public:
void fun(int s) {
cout << "b";
}
};
class c :public a {
};
int main() {
b* b1 = new b();
b1->fun(2); //子类中重新实现
c* c1 = new c();
c1->fun();//子类中没有重新实现
}
重写
#include<iostream>
using namespace std;
class a {
public:
virtual void fun() {
cout << "a"<<endl;
}
void fun2() {
cout << "a no virtual" << endl;
}
};
class b:public a {
public:
void fun() {
cout << "b"<<endl;
}
};
class c :public a {
void fun(int cval) {
cout << "c" << endl;
}
void fun2() {
cout << "c no virtual" << endl;
}
};
int main() {
a* b1 = new b();
b1->fun();//b中重写
a* c1 = new c();
c1->fun();//c中无重写
c1->fun2();
}
网友评论