c++ 类的动态类型和静态类型

基类的指针或引用会根据运行时绑定的对象,动态的选择是执行基类的虚函数还是派生类的虚函数。对于非虚函数的成员访问,比如调用非虚成员函数,或访问成员属性,只能访问指针或引用所指定的静态类型(这里指基类)的非虚成员,而不管动态类型是什么。
也就是说多态是针对虚函数来说的。

以下是测试代码:

//test for dynamic_cast

#include <iostream>

using namespace std;

class Base {
public: 
        string name = "parent";
        virtual void who() {
                cout << "i am parent." << endl;
        }
        
        void p() {
                cout << "parent" << endl;
        }
};

class Child : public Base {
public:
        string name = "child";

        void who() override {
                cout << "i am son." << endl;
        }

        void c() {
                cout << "child" << endl;
        }
};


int main(void) {

        //test pointer
        {
                Base* pb = new Base();
                Child* pc = new Child();

                auto p = dynamic_cast<Base*> (pc);
                p -> who();    //child
                p -> Base::who();  //parent.
                cout << p -> name << endl;  //parent
                cout << dynamic_cast<Child*> (p) -> name << endl;  //child
                p -> p(); //parent
                //p -> c();  //error, no member named c()
                dynamic_cast<Child*> (p) -> p();
                dynamic_cast<Child*> (p) -> c();

                cout << endl;

                delete pb, pc;
        }

        //test reference
        {
                cout << endl << "test ref" << endl;

                Child child;
                Base &ref = child;

                //virtual func
                ref.who();  // son
                ref.Base::who();  //parent

                //general member data
                cout << ref.name << endl; //parent
                cout << dynamic_cast<Child&> (ref).name << endl; //child

                //general member function
                ref.p();
                //ref.c();  //error, no member c()
                dynamic_cast<Child&> (ref).c();
                dynamic_cast<Child&> (ref).p();   //correct
        }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值