我正在處理多個類和檔案,所以我創建了這個虛擬代碼來更好地定義我的問題。我有一個父類Parent和一個子類Child。我已經將這兩個檔案分開在一個 .h 和一個 .cpp 檔案中
父母.h
class Parent
{
Parent(int a, int b, int c);
protected:
void somefunc();
};
父級.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";
}
孩子.h
#include "parent.h"
class Child : public Parent
{
public:
void funk();
};
孩子.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 的建構式,但我不知道該怎么做。
- 我該如何擺脫這個錯誤?
- 如果錯誤與此無關,當它繼承一個在其建構式中具有引數的類時,如何創建子類的物件?我還需要呼叫引數建構式,所以我不能只創建另一個空白建構式并使用它。
uj5u.com熱心網友回復:
我該如何擺脫這個錯誤?
您可以通過在類中添加默認建構式來解決此錯誤,Parent如下所示。另外,請注意,您需要制作 constrcutors public。
父母.h
class Parent
{ public: //ADDED PUBLIC KEYWORD
Parent(int a, int b, int c);
//ADD DEFAULT CONSTRCUTOR
Parent()=default;
protected:
void somefunc();
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/408685.html
標籤:
