多态调用规则

多态调用规则

#include 
class A {
public:
    int a;
    virtual void Test() {
        std::cout << "A::Test:" << a << std::endl;
        this->a = 100;
        std::cout << "A::Test:" << a << std::endl;
        delete this;
    }
};

class B : public A {
public:
    void Test() {
        std::cout << "B::Test" << std::endl;
    }
};

/*
1、对于指针调用, A* a1 = new B();如果函数同名但是没有加virtually,那么会调用A::Test(),如果加了virtual,那么会调用B::Test()
2、对于引用调用,A& a = b;如果函数同名但是没有加virtually,那么会调用A::Test(),如果加了virtual,那么会调用B::Test()
3、对于对象调用,A a = b;不管加不加virtually,都会调用A::Test(),除非强转为B类类型,才会调用B::Test()
*/
int main() {
    
    A* a1 = new B();
    a1->Test(); //B::Test

    B b;
    A &a = b;
    a.Test();  //B::Test

    B b1;
    A a2 = b1;
    a2.Test();  //A::Test    这里会报错因为只有new出来的对象才能使用delete,普通对象不行
}





你可能感兴趣的:(c++)