简体   繁体   中英

How do I define the non-member constructor of a derived class (within class header)

I'm a C++ beginner. I've learnt how to define derived class constructor as a class member:

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

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

Now, I thought the same principle would work for non-member definition of derived class' constructor as well:

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){}

but instead, I'm getting this error in 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

You are close. To move the constructor body definition (or any class method definition) outside of the class declaration, you need to remove the body definition from the class declaration. You did that for A , you need to do it for B as well.

Also, you are missing the closing ; on the class declarations.

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)
{
}

A member initializer list cannot be specified in a pure declaration,

B(param1OfA, param2OfA, params) :A(param1OfA, param2OfA);

Make that

B(param1OfA, param2OfA, params);

Also, there's a missing semicolon at the end of this class definition:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM