Coisíní755 2022-04-06 09:44 采纳率: 50%
浏览 2238

始终初始化成员变量怎么解决

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#include<iostream>
using namespace std;



class CBase1
{
public:
    CBase1() {}
    CBase1( int a)
        :a(a)
    {
        cout << "base1 structure..." << endl;
    }
    ~CBase1()
    {
        cout << "base1 destructure..." << endl;
    }
    void print()
    {
        cout << "a=" << a << endl;
    }
protected:
    int a;
};
class CBase2
{
public:
    CBase2() {}
    CBase2(int b)
        :b(b)
    {
        cout << "base2 structure..." << endl;
    }
    ~CBase2()
    {
        cout << "base2 destructure..." << endl;
    }
    void print()
    {
        cout << "b=" << b << endl;
    }
protected:
    int b;
};
class CDerive : public CBase1, public CBase2 
{
public:
    
    CDerive() 
    {
        cout << "derive structure..." << endl;
    }
    ~CDerive()
    {
        cout << "derive destructure..." << endl;
    }
    void print()
    {
        CBase1::print();
        CBase2::print();
        b1.print();
        b2.print();
        cout << "c=" << c << endl;
    }
private:
    CBase1 b1;
    CBase2 b2;
    int c;
};

int main()
{
    CDerive d;
    d.print();
}



运行结果及报错内容

警告 C26495 未初始化变量 CBase1::a。始终初始化成员变量(type.6)。
未初始化变量 CBase2::b。始终初始化成员变量(type.6)。

警告 C26495 未初始化变量 CDerive::c。始终初始化成员变量(type.6)。

我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

3条回答 默认 最新

  • Frank_Liuxing 2022-04-06 10:12
    关注

    首先,这个警告是值得重视的,如果你调用了不带参数构造函数CBase1(),请问你的成员变量的初始值是多少,因为你没有赋值过,它可能是随机值。所以,关键看你希望它是多少,例如,你希望调用CBase1()时,成员变量a的值是0,你可以这样写:

      CBase1() :a(0)
    {
    }
    

    同理,CBase2的无参构造函数。
    在你的代码中,CDerive确实会调用父类的无参构造函数。

    评论

报告相同问题?

问题事件

  • 请采纳用户回复 4月7日
  • 创建了问题 4月6日