constructor和destructor不可以调用virtual函数

/* 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值