继承和默认构造函数

时间:2016-12-08 18:03:04

标签: c++

我有一个类A,我只能通过A(int arg1)构造函数实例化,并且我从类B派生的类A我想要实例化只能通过B(int arg1, int arg2)构造函数。

以下是示例:

class A
{
public:
    int i;
    A(int arg1)
    {
        i= arg1;
    }
};

class B : public A
{
    int j;

    B(int arg1, int arg2)
    {
        i= arg1;
        j= arg2;
    }
};

产生错误:

inheritance_default_constructor.cpp: In constructor ‘B::B(int, int)’:
inheritance_default_constructor.cpp:16:6: error: no matching function for call to ‘A::A()’
      {
      ^
inheritance_default_constructor.cpp:16:6: note: candidates are:
inheritance_default_constructor.cpp:5:6: note: A::A(int)
      A(int arg1)

我可以这样解决:

class A
{
public:
    int i;
    A(int arg1)
    {
        i= arg1;
    }
};

class B : public A
{
    int j;

    B(int arg1, int arg2) : A(arg1)
    {
        j= arg2;
    }
};

但是,如果我需要B(int arg1, int arg2)构造函数的主体不在.h文件中,而在.cpp文件中,是否可能呢?

更新

我做错了:

//inheritance_default_constructor.h
class A
{
public:
   int i;
   A(int arg1)
   {
        i= arg1;
   }
};

class B : public A
{
    int j;

    B(int arg1, int arg2) : A(arg1);
};


//inheritance_default_constructor.cpp
#include "inheritance_default_constructor.h"

B::B(int arg1, int arg2) : A(arg1)
{
    j= arg2;
}

int main()
{
    return 0;
}

In file included from inheritance_default_constructor.cpp:1:0:
inheritance_default_constructor.h: In constructor ‘B::B(int, int)’:
inheritance_default_constructor.h:15:32: error: expected ‘{’ at end of input
  B(int arg1, int arg2) : A(arg1);
                                ^
inheritance_default_constructor.cpp: At global scope:
inheritance_default_constructor.cpp:3:1: error: redefinition of ‘B::B(int, int)’
 B::B(int arg1, int arg2) : A(arg1)
 ^
In file included from inheritance_default_constructor.cpp:1:0:
inheritance_default_constructor.h:15:2: error: ‘B::B(int, int)’ previously defined here
  B(int arg1, int arg2) : A(arg1);

2 个答案:

答案 0 :(得分:3)

简单地说:是的,这是可能的。语法如下。

file.h

class A
{
public:
    int i;
    A(int arg1)
    {
        i= arg1;
    }
};

class B : public A
{
    int j;

    B(int arg1, int arg2);
};

file.cpp

B::B(int arg1, int arg2): A(arg1)
{
    j= arg2;
}

答案 1 :(得分:0)

是的,这是可能的。您可以在.cpp文件中编写B的构造函数,就像在.h文件中一样。