“C++动态绑定”相关问题探讨

一、相关问题:

1. 基类、派生类的构造和析构顺序

2. 基类、派生类中virtual的取舍

二、测试代码:

#include <iostream>
class A {
public:
    A() {
        std::cout  << "A()" << std::endl;
    }
    virtual void print() { std::cout << "A print()" << std::endl; }
    virtual ~A() {
        std::cout  << "~A()" << std::endl;
    }
};
class B : public A {
public:
    B() : A(){
        std::cout  << "B()" << std::endl;
    }
    virtual void print() { std::cout << "B print()" << std::endl; }
    virtual ~B() {
        std::cout  << "~B()" << std::endl;
    }
};
void print() {

}
int main(int argc, char *argv[])
{
    A* c = new B();
    c->print();
    delete c;
    return 0;
}

三、探讨与结论:

1. 基类、派生类的构造和析构顺序为:基类构造-派生类构造-派生类析构-基类析构

上述代码输出结果为:

2. 基类、派生类中virtual的取舍:若要实现动态绑定,基类中virtual关键字不可舍弃,派生类中virtual关键字可有可无;若基类中有关键字virtual,则普通函数调用派生类函数,析构函数先调用派生类,再调用基类;若基类中无关键字virtual,则普通函数和析构函数均只调用基类函数。

测试代码1:基类无关键字virtual

#include <iostream>
class A {
public:
    A() {
        std::cout  << "A()" << std::endl;
    }
    void print() { std::cout << "A print()" << std::endl; }
    ~A() {
        std::cout  << "~A()" << std::endl;
    }
};
class B : public A {
public:
    B() : A(){
        std::cout  << "B()" << std::endl;
    }
    virtual void print() { std::cout << "B print()" << std::endl; }
    virtual ~B() {
        std::cout  << "~B()" << std::endl;
    }
};
void print() {

}
int main(int argc, char *argv[])
{
    A* c = new B();
    c->print();
    delete c;
    return 0;
}

输出结果为:

测试代码2:派生类无关键字virtual

#include <iostream>
class A {
public:
    A() {
        std::cout  << "A()" << std::endl;
    }
    virtual void print() { std::cout << "A print()" << std::endl; }
    virtual ~A() {
        std::cout  << "~A()" << std::endl;
    }
};
class B : public A {
public:
    B() : A(){
        std::cout  << "B()" << std::endl;
    }
    void print() { std::cout << "B print()" << std::endl; }
    ~B() {
        std::cout  << "~B()" << std::endl;
    }
};
void print() {

}
int main(int argc, char *argv[])
{
    A* c = new B();
    c->print();
    delete c;
    return 0;
}

输出结果为:

(0)

相关推荐