【问题标题】:How do I call an object of a class that inherits another class that has arguments in its constructor?如何调用一个类的对象,该类继承了另一个在其构造函数中具有参数的类?
【发布时间】:2022-01-11 11:33:55
【问题描述】:

我正在处理多个类和文件,因此我创建了这个虚拟代码来更好地定义我的问题。我有一个父类Parent 和一个子类Child。我已将这两个文件分别放在一个 .h 和一个 .cpp 文件中

parent.h

class Parent
{
    Parent(int a, int b, int c);
    protected:
        void somefunc();
         
};

parent.cpp

#include<iostream>
#include "parent.h"

Parent::Parent(int a, int b, int c)
{
    std::cout<<"Answer is: "<<a+b+c;
}
void Parent::somefunc()
{
    std::cout << "I am some func";
}

child.h

#include "parent.h"
class Child : public Parent
{
    public:
    void funk();
};

child.cpp

    #include"child.h"    
    void Child::funk()
    {
        somefunc();
    }

我正在使用另一个文件 running.cpp 来运行它。

    #include "child.h"
    int main()
    {
        Child a;
        a.funk();
        return 0;
    }

尝试使用 g++ 构建它,给了我错误:

running.cpp: In function ‘int main()’:
running.cpp:4:11: error: use of deleted function ‘Child::Child()’
     Child a;
           ^
In file included from running.cpp:1:0:
child.h:2:7: note: ‘Child::Child()’ is implicitly deleted because the default definition would be ill-formed:
 class Child : public Parent
       ^~~~~
child.h:2:7: error: no matching function for call to ‘Parent::Parent()’
In file included from child.h:1:0,
                 from running.cpp:1:
parent.h:3:5: note: candidate: Parent::Parent(int, int, int)
     Parent(int a, int b, int c);
     ^~~~~~
parent.h:3:5: note:   candidate expects 3 arguments, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(const Parent&)
 class Parent
       ^~~~~~
parent.h:1:7: note:   candidate expects 1 argument, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(Parent&&)
parent.h:1:7: note:   candidate expects 1 argument, 0 provided

我使用的 g++ 命令是g++ *.cpp -o test

我知道我应该以某种方式提供参数来运行 Parent 的构造函数,但我不知道该怎么做。

  1. 如何消除此错误?
  2. 如果错误与此无关,当子类继承其构造函数中具有参数的类时,如何创建子类的对象?我还需要调用参数构造函数,所以我不能只创建另一个空白构造函数并使用它。

【问题讨论】:

  • 你声明了Child构造函数,但是你在哪里定义(实现)它?
  • 错误告诉你声明了Child::Child()但你没有实现它。
  • 感谢您的关注,我正在自己测试一些东西,但在发布之前没有正确恢复。编辑了问题!
  • 还是一样的问题,只是上移了一步:你声明了Parent默认构造函数,但是你从来没有定义(实现)它。
  • 仍然是那个基本错误。再次改变

标签: c++ class oop inheritance g++


【解决方案1】:

如何摆脱这个错误?

您可以通过在Parent 类中添加默认构造函数来解决此错误,如下所示。另外,请注意,您需要将构造函数设为 public。

parent.h

class Parent
{   public: //ADDED PUBLIC KEYWORD
        Parent(int a, int b, int c);
        //ADD DEFAULT CONSTRCUTOR
        Parent()=default;
    protected:
        void somefunc();
         
};

【讨论】:

  • 然后需要调用Parent的构造函数。
  • 感谢您的关注,我正在自己测试一些东西,但在发帖之前没有正确还原。编辑了问题!
  • 仍然是那个基本错误。再次改变
  • @VisheshVarma 你为什么要一次又一次地改变你的问题?
  • 是的,就像我之前的编辑一样,这也是一个疏忽。我又换了一次问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
相关资源
最近更新 更多