錯誤:描述資源路徑位置型別沒有匹配函式呼叫'Saat::Saat()' Ucus.cpp /project9/src line 4 C/C 問題
我的這個班級叫Saat
#ifndef SAAT_H_
#define SAAT_H_
#include <string>
class Saat {
public:
Saat(int, int);
std::string to_string() const;
private:
int saat, dakika;
};
#endif /* SAAT_H_ */
#include "Saat.h"
Saat::Saat(int s, int d){
saat = s;
dakika = d;
}
std::string Saat::to_string() const{
return std::to_string(saat) ":" std::to_string(dakika);
}
這是我的班級 Ucus
#ifndef UCUS_H_
#define UCUS_H_
#include <string>
#include "Saat.h"
class Ucus {
public:
Ucus(std::string, std::string, std::string, Saat);
static int get_ucus_sayisi();
std::string to_string();
private:
std::string cikisSehir;
std::string varisSehir;
std::string ucusNo;
Saat kalkis_saati;
static int ucus_sayisi;
};
#endif /* UCUS_H_ */
#include "Ucus.h"
/*ERROR IS HERE */Ucus::Ucus(std::string cs, std::string vs, std::string un, Saat s) {
cikisSehir = cs;
varisSehir = vs;
ucusNo = un;
kalkis_saati = s;
}
int Ucus::get_ucus_sayisi(){
return ucus_sayisi;
}
std::string Ucus::to_string(){
return cikisSehir varisSehir ucusNo kalkis_saati.to_string();
}
我正在觀看有關課程的視頻,我想在 Ucus 課程中使用我的 Saat 課程。我在視頻中做同樣的事情,但它給了我這個錯誤:***(描述資源路徑位置型別沒有匹配函式呼叫'Saat::Saat()' Ucus.cpp /project9/src line 4 C/C 問題 )
沒有什么不同,但對我不起作用。
uj5u.com熱心網友回復:
在類中,成員是在進入建構式的主體之前創建的。您的代碼試圖默認構造一個 Saat,然后通過賦值在正文中覆寫它。
因為您的 Saat 類沒有默認建構式,所以您的代碼無法編譯。為什么你的類沒有默認建構式?如果您不提供任何建構式,編譯器可以為您生成一個,但是一旦您撰寫了一個,則不再提供默認建構式而無需請求。但如果這個編譯你會稍微更糟。發現一個錯誤而不是默默地忍受它是件好事。
執行此操作的正確方法是不默認構造您的物件,而是在建構式成員初始值設定項串列中復制構造它和其他成員:
Ucus::Ucus(std::string cs, std::string vs, std::string un, Saat s)
cikisSehir{cs},
varisSehir{vs},
ucusNo{un},
kalkis_saati{s},
{
}
它也更有效率。沒有理由創建一個物件,然后通過賦值覆寫它。最好通過副本直接創建它,這是一個您將自動生成的建構式(除非您有一個不可復制的成員,但在您的情況下您沒有。)
當然,你真的應該考慮傳入你的字串std::string const &,以避免不必要的副本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/457166.html
