zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    类的创建
    线性规划
    break、continue、pass介绍
    array numpy 模块
    hive字符串函数
    进化的Spark, 从DataFrame说起
    hive sql split 分隔符
    Spark On YARN内存分配
    浅谈Spark应用程序的性能调优
    Spark-Mllib(二)基本统计
  • 原文地址:https://www.cnblogs.com/findumars/p/3063790.html
Copyright © 2011-2022 走看看