/* constructor和destructor不可以调用virtual函数
constructor: 因为构造derived类的对象的时候首先调用base类的constructor,
而base类里调用virtual函数是调用base类里的实现,这可能和预期想调用derived类中的virtual函数相违背,
即使调用的是derived类中的virtual函数,但此时derived类的对象并没有构造出来,这就导致virtual函数使用未初始化的local成员变量
甚至base类中的virtual函数是pure virtual,调用是没有意义的;
destructor: 析构的时候首先析构derived类,再析构base类,因此调用的virtual函数实际是base类中的而不是derived类中的,这未必是代码设计的本意,
纵使调用的是derived类中的virtual函数,那么virtual函数可能会使用到derived类对象已经释放的local成员(变成了未初始化的成员) */
/* 如果在base类中需要调用函数,则使用non-vitrual函数吧,其所需的参数可由derived类的static函数传给base类的构造函数,
注意一定要用derived类的static函数,因为使用static时才不会使用derived类的非静态(未初始化)成员 */
#include <string>
#include <iostream>
class Fruit
{
public:
Fruit(const std::string &color = "", bool test_good = true){
m_color = color;
m_test_good = test_good;
changeColor(test_good);
}
/* 静态成员函数只能修改静态成员;在静态成员函数中不能修改非静态成员,因为非静态成员必须归属于某个对象
静态成员函数不能是const的,因为const实际是作用于*this的,而*this是个对象,但静态成员函数不属于任何一个对象 */
void changeColor(bool is_test_good) {
if (!is_test_good)
{
// 味道不好,可能坏了,颜色黑了O(∩_∩)O
m_color = "black";
}
}
protected:
std::string m_color;
bool m_test_good;
};
class Apple : public Fruit
{
public:
Apple(const std::string &color="red") :
Fruit(color, isAlter()){
}
private:
static bool isAlter() {
if (m_weight >= 0.5f)
{
return true;
}
else
{
return false;
}
}
private:
static float m_weight;
};
float Apple::m_weight = 0.6f;
int main() {
Apple apple("red");
return true;
}
constructor和destructor不可以调用virtual函数
最新推荐文章于 2021-05-14 09:19:58 发布