“C++动态绑定”相关问题探讨
程序员文章站
2022-04-16 09:11:09
一、相关问题: 1. 基类、派生类的构造和析构顺序 2. 基类、派生类中virtual的取舍 二、测试代码: 三、探讨与结论: 1. 基类、派生类的构造和析构顺序为:基类构造-派生类构造-派生类析构-基类析构 上述代码输出结果为: 2. 基类、派生类中virtual的取舍:若要实现动态绑定,基类中v ......
一、相关问题:
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;
}
输出结果为:
上一篇: Go学习笔记01
下一篇: 程序员之殇:而立之年,何处何从?