「生活可以更简单, 欢迎来到我的开源世界」
关于函数重写
2020-12-17
C++

关于函数重写

#include <iostream>
#include <atomic>

using std::cin;
using std::cout;
using std::endl;

class People {
public:
void say() { cout << "people say" << endl;}
virtual void eat(){};
};

class Man : public People {
public:
void say() { cout << "man say" << endl;}
void eat() { cout << "man eat" << endl;}
};

int main(int argc, char* argv[]){
Man man;
man.say();/*man say */
man.eat();/*man eat */

People* man2 = new Man();
man2 -> say();/*people say */
man2 -> eat();/*man eat */

People& man3 = man;
man3.say();/*people say */
man3.eat();/*man eat */

People& man4 = *man2;
man4.say();/*people say */
man4.eat();/*man eat */

return 0;
}

总结:普通重写和虚函数重写,一般情况区别不大,得涉及指针或者引用才会动态分发

<⇧>