将参数传递给类外的基类构造函数

时间:2015-04-18 11:01:51

标签: c++ constructor

我想在Derived类之外定义构造函数。我怎样才能实现这一点。如果我在类中定义了构造函数,它就可以工作。

感谢任何帮助。

以下是我的代码。

class Base
{
    private:
        int var1;
    public:
        Base();
        Base(int var1);
        ~Base();
        void print()
        {
            cout<<"Base"<<endl;
        }
};

class Derived:public Base
{
    private:
        int var2;
    public:
        Derived();
        Derived(int var2,int var1):Base(var1);
        ~Derived();
        void print()
        {
            cout<<"Derived"<<endl;
        }

};

Base::Base()
{
    cout<<"Constructing Base"<<endl;
}

Base::Base(int var1)
{
    cout<<"Constructing Base with "<<var1<<endl;
}

Base::~Base()
{
    cout<<"Destructing Base"<<endl;
}

Derived::Derived()
{
    cout<<"Constructing Derived"<<endl;
}

Derived::Derived(int var2,int var1):Base(var1)
{
    cout<<"Constructing Derived with "<<var2<<endl;
    this->var2 = var2;
}

Derived::~Derived()
{
    cout<<"Destructing Derived"<<endl;
}

int main()
{
    Derived d = Derived(2,1);
    d.print();

    return 0;
}

我在编译时收到以下错误。

derive.cpp: In constructor ‘Derived::Derived(int, int)’:
derive.cpp:25:45: error: expected ‘{’ at end of input
         Derived(int var2,int var1):Base(var1);
                                             ^
derive.cpp: At global scope:
derive.cpp:54:1: error: redefinition of ‘Derived::Derived(int, int)’
 Derived::Derived(int var2,int var1):Base(var1)
 ^
derive.cpp:25:9: error: ‘Derived::Derived(int, int)’ previously defined here
         Derived(int var2,int var1):Base(var1);

1 个答案:

答案 0 :(得分:3)

调用基类构造函数是实现。因此,它不属于类声明。 构造函数声明为

Derived(int var2, int var1);

你的实施很好。