C++多态必须使用指针或者引用,直接传对象就变成切片

C++ 多态必须使用指针或者引用,直接传对象就变成切片。虚函数的魔力只对指针和引用有效。按值传递对象不允许调用虚函数。

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

class base {
public:
virtual void print() {
cout<<"it is in base::print"<<endl;
}
virtual ~base(){}
};

class son:public base {
public:
virtual void print() {
cout<<"it is in son::print"<<endl;
}
virtual ~son(){}
};

class grandson:public son {
public:
virtual void print() {
cout<<"it is in grandson::print"<<endl;
}
virtual ~grandson(){}
};

void fun(base arge) { // 基类对print()的调用
arge.print();
}
void func(base& arge) { // 静态多态
arge.print();
}

void func_t(base* arge){ // 动态多态
arge->print();
}

int main() {
base a;
son b;
grandson c;
func_t(&a);// good
func_t(&b);
func_t(&c);

base d;
son e;
grandson f;
func(d); // good
func(e);
func(f);

base g;
son h;
grandson i;
fun(g);// 不体现多态,都是调用的base类的print方法
fun(h);// 不体现多态,都是调用的base类的print方法
fun(i);// 不体现多态,都是调用的base类的print方法
return 0;
}

原文地址:https://www.cnblogs.com/findumars/p/3063790.html