[英]why am I getting the following errors : In constructor 'B::B(int, int)': no matching function for call to 'A::A()'
[英]error: no matching function for call to 'b::b()'
嗨,我只是開始用C ++編程,但是我有一個問題。 我嘗試在其他班級中創建一個班級,但是它不起作用...能幫我嗎?
這是我的主要:
#include <iostream>
#include "a.hpp"
#include "b.hpp"
using namespace std;
int main()
{
return 0;
}
這是我的第一堂課cpp:
#include <iostream>
#include "a.hpp"
using namespace std;
a::a(){} /* The problem is here :error: no matching function for call
to 'b::b()*/
a::~a(){}
void a::write()
{
cout << "Write a number : " << endl;
cin >> m_number;
}
這是hpp:
#ifndef A_HPP_INCLUDED
#define A_HPP_INCLUDED
#include "b.hpp"
class a : public b
{
public:
a();
~a();
void write();
protected:
int m_number;
};
#endif // INTERFACE_HPP_INCLUDED
B類cpp:
#include <iostream>
#include "b.hpp"
using namespace std;
b::b(double c, double d){m_c = c; m_d = d}
b::~b(){}
void b::write1()
{
cout << m_c+m_d<< endl;
}
和hpp:
#ifndef B_HPP_INCLUDED
#define B_HPP_INCLUDED
class b
{
public:
b(double c, double d);
~b();
void writed1();
protected:
double m_c;
double m_d;
};
#endif // B_HPP_INCLUDED
非常感謝你的幫助 !!!
類b
的唯一構造函數采用兩個double
參數。
類a
是從b
派生的,但是類a
無法使用其兩個必需參數來調用其超類的構造函數,並且其超類b
沒有默認的構造函數。
如果您的類的構造函數具有必需的參數,並且該類沒有默認的構造函數,並且您從該類派生,則派生的類負責構造其超類,並使用必需的參數來調用其構造函數。
當您定義沒有構造函數的類時,C ++會為您生成一個默認構造函數。 例如,如果我們編寫一個“簡單的舊結構”:
struct b {
int x;
};
那么實際上就好像我們有一個默認的構造函數b()
,它什么也不做。 這使我們可以編寫:
b bvar;
但是,當我們引入構造函數時,將禁止編譯器生成的默認構造函數:
class b {
public:
b(int i, double d);
};
該類只有一個構造函數: b(int, double)
。 如果不調用此構造函數並將其傳遞兩個參數,則無法構造對象:
b bvar; // error: no b::b() function.
即使我們從此類繼承來創建一個具有默認構造函數的派生類a
,也是如此:
class a : public b {
public:
a();
};
a::a()
{
}
因為我們沒有在a::a()
構造函數中顯式初始化基b
,所以C ++編譯器希望使用默認構造來創建對象的b
部分。 但是,可惜, b
沒有默認構造函數!
有兩種方法。 一是明確語法加入到a
構造函數初始化b
的部分a
,是這樣的:
a() : b(0, 3.5)
{
}
此C ++特殊的base / member初始化語法,可在構造函數中使用以指定如何初始化成員和基礎對象。 通過這種方式,您可以將所需的構造函數參數傳遞給他們。
第二種解決方案是在b
添加默認構造函數,或者修改其現有的構造函數,使其可以充當默認構造函數。 讓我們采用第二種方法:
class b {
public:
b(int i = 0, double d = 0.0);
};
我們要做的是為兩個參數都賦予默認值,使其成為可選值。 由於現在可以將b(int, double)
構造函數稱為不帶參數的b()
,因此可以滿足默認構造函數的需要。
順便說一下,可以為基和成員指定多個初始化器。 初始化按照定義它們的順序進行,而不是按照初始化程序的寫入順序進行:
class foo : public bar {
xyzzy xy;
int count;
public:
foo(const string &arg)
: bar(arg) // let's assume the base constructor takes a string
, xy(42, 9) // class xyzzy has a constructor that takes a pair of integers
, count(0) // member, initialized to zero.
{
}
}
這也說明了在程序文本中布置這些初始化器的一種不錯的方法,冒號和逗號在左邊,就像它們是前綴一樣。
只要有可能,就應該以這種方式初始化成員,而不是讓它們進行默認初始化,並用構造函數主體中的賦值覆蓋成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.