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/archive/2013/05/06/3063790.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/87298

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午11:02
下一篇 2023年2月9日 下午11:02

相关推荐