我对 Weffc++
警告有理解上的问题。
main.cpp: In constructor ‘B::B()’: main.cpp:13:1: warning: ‘B::a’ should be initialized in the member initialization list [-Weffc++] B(){} ^
#include <iostream>
class A
{
public:
A() {}
~A() {}
void test() { std::cout << "Hello world\n"; }
};
class B
{
public:
B() {}
~B() {}
A a;
};
int main()
{
B b;
b.a.test();
return 1;
}
如果我编写或使用初始化列表,我没有问题。
A a = {};
我以为默认构造函数会自动调用?为什么我必须显式使用他?
最佳答案
I thought the default constructor will called automatically?
会的。
Why I have to use him explicit ?
你不知道。
I have an understanding problem for the Weffc++ warning
就是这样。一个警告。如果我们查看 the documentation ,我们发现 -Weffc++
代表一个风格指南,仅此而已。是否要遵循迈耶斯的风格完全取决于您。
如果你确实想听从建议,你可以这样做:
class B
{
public:
B() : a() {} // <-- a() in the ctor-initialiser
~B() {}
A a;
};
……或者以您已经展示的方式。
坦率地说,我不会打扰。我不使用 -Weffc++
设置。
关于c++ - GCC -Weffc++ 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43188038/