如何定义派生类的非成员构造函数(在类头中)

时间:2016-06-26 06:42:00

标签: c++ class inheritance constructor

我是C ++初学者。我已经学会了如何将派生类构造函数定义为类成员:

class A{
    ...
    public:
    A(params){}
};

class B :public A{
    ...
    public:
    B(param1OfA, param2OfA, params) :A(param1OfA, param2OfA){}
};

现在,我认为同样的原则也适用于派生类'构造函数的非成员定义:

class A{
    ...
    public:
    A(params);
}

A::A(params){};

class B :public A{
    ...
    public:
    B(param1OfA, param2OfA, params) :A(param1OfA, param2OfA);
};

B::B(param1OfA, param2OfA, params) :A(param1OfA, param2OfA){}

但相反,我在Visual Studio中收到此错误:

1>  Source.cpp
1>d:\webdev\c++\godina ii - parcijala-i\aa-vjezba-polimorfizam\source.cpp(63): error C2969: syntax error : ';' : expected member function definition to end with '}'
1>d:\webdev\c++\godina ii - parcijala-i\aa-vjezba-polimorfizam\source.cpp(67): error C2144: syntax error : 'std::string' should be preceded by ')'
1>d:\webdev\c++\godina ii - parcijala-i\aa-vjezba-polimorfizam\source.cpp(67): error C2630: ';' found in what should be a comma-separated list
1>d:\webdev\c++\godina ii - parcijala-i\aa-vjezba-polimorfizam\source.cpp(67): error C2612: trailing 'type' illegal in base/member initializer list
1>d:\webdev\c++\godina ii - parcijala-i\aa-vjezba-polimorfizam\source.cpp(84): fatal error C1004: unexpected end-of-file found

2 个答案:

答案 0 :(得分:1)

你很亲密。要在类声明之外移动构造函数体定义(或任何类方法定义),需要从类声明中删除主体定义。您为A执行了此操作,您还需要为B执行此操作。

此外,您缺少关于类声明的结束;

class A
{
    ...
public:
    A(params);
};

A::A(params)
{
}

class B : public A
{
    ...
public:
    B(param1OfA, param2OfA, params);
};

B::B(param1OfA, param2OfA, params)
    : A(param1OfA, param2OfA)
{
}

答案 1 :(得分:1)

无法在纯声明

中指定成员初始值设定项列表
B(param1OfA, param2OfA, params) :A(param1OfA, param2OfA);

制作

B(param1OfA, param2OfA, params);

此外,在此类定义的末尾还有一个缺少的分号:

class A{
    ...
    public:
    A(params);
}