c++ - 在类的成员变量定义时,使用此变量的带参数的构造函数来初始化,被编译器误解、报错。如何才能达到目的?
ringa_lee
ringa_lee 2017-04-17 15:03:04
0
3
559
using namespace std;

class A
{
public:
    A(int a) :m(a) {};
    void show() {
        cout << "m=" << m << endl;
    }
private:
    int m;
};

class B
{
public:
    A aa(5);//VS2015此处报错:“应输入类型说明符”。
//说明编译器把此处理解成了:声明一个名为aa、返回值为A,有一个入参的成员函数了。
//而本来的意图只是想定义一个名为aa的成员对象
};

int main(void)
{
    A a(44);
    a.show();
    return 0;
}
ringa_lee
ringa_lee

ringa_lee

reply all(3)
Ty80

You are overthinking it. Your usage is wrong. Class member variables cannot be declared like this

A aa(5); // !! 错误
A aa = 5; // OK 需要c++11,当然VS2015默认支持
A aa{5}; // OK

Except for constructor calls without parameters, other constructor calls are unambiguous because function calls use actual parameters and do not have type declarations. How can they be misunderstood as function declarations

Ty80

If you are using a compiler that supports C++11 or above, you can initialize member variables when the class is defined.
The error reported by the compiler is correct. You cannot use parentheses to initialize this member here. You can use initialize list, or use the equal sign directly.

class B
{
public:
    A aa{5};
    // A aa = 5;
};

Of course there are some details you can refer to the document:
http://en.cppreference.com/w/...

迷茫

Either change it to a static member or initialize it in the constructor.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template