c++ - 为什么?从未初始化的父类成员隐式初始化

标签 c++ oop compiler-warnings

我在 C++ 初始化方面有过糟糕的经历,我想看看是否有一个真实世界的例子可以证明编译器没有发出警告。

下面的代码编译正确,但是 foo 和 bar 被初始化为 uninit 值(我假设来自未初始化的父类)。 g++ 和 VS 的编译器不会发出任何警告。 我当然被告知,让成员公开并且不装饰它们是不好的行为。但是,我假设编译器可以发现这种不一致,并且至少会发出最高警告级别的警告,因为我看不到此类代码的任何应用。

#include <iostream>
using namespace std;

class base_class {
    public:
        int foo;
        int bar;

    base_class(int foo,int bar):
        foo(foo),bar(bar) 
    {}
};

class derived_class: public base_class {
    public:
    derived_class(int Foo, int Bar):
        base_class(foo,bar)
    { 
                    int a = Foo * Bar;

                    a++;
                    cout << foo << " " << bar << endl;
    }
};

int main ()
{
    derived_class *buzz = new derived_class(1,2);
    buzz->print();
}

最佳答案

我认为你的问题是你的构造函数参数用大写字母:

通过以下代码,我得到了正确的值:

#include <iostream>
using namespace std;

class base_class {
    public:
        int foo;
        int bar;

    base_class(int foo,int bar):
        foo(foo),bar(bar)
        {
        int a = foo * bar;

        a++;

        cout << "Base : " << foo << ", " << bar << ", " << a << endl;
    }

};

class derived_class: public base_class {
    public:
    derived_class(int foo, int bar):
        base_class(foo,bar)
    {
        cout << "derived : " << foo << ", " << bar << endl;
    }
};

int main ()
{
    derived_class baz(1,2);
}

输出:

Base : 1, 2, 3
derived : 1, 2

然后发生的事情是您的成员使用未初始化的成员值“初始化”:)

我的2c

关于c++ - 为什么?从未初始化的父类成员隐式初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3083134/

相关文章:

c++ - 查找融合图中元素的索引

c++ - 函数指针及其调用参数

javascript - javascript/node 中的单元测试嵌套对象

面向对象。选择对象

c - "assignment makes integer from pointer without a cast"在 c

c# - 当仅覆盖一对方法或属性中的一个时显示警告

c++ - 删除没有指定大小的指针数组

c++ - 从 3d 模型截取屏幕截图

c++ - 排序a、b、c是否等价于排序c;对 b 进行排序;排序一个?

java - 如何从 javac 获得更多警告?