這是代碼:在構造函數中,候選人預計1個參數,提供0
class cat
{
private:
int height;
public:
cat (int inputHeight);
};
cat::cat (int inputHeight)
{
height = inputHeight;
}
class twoCats
{
private:
cat firstCat;
cat secondCat;
public:
twoCats (cat theFirstCat);
void addSecondCat (cat theSecondCat);
};
twoCats::twoCats (cat theFirstCat)
{
firstCat = theFirstCat;
}
void twoCats::addSecondCat (cat theSecondCat)
{
secondCat = theSecondCat;
}
int main() {return 0;}
而且這些都是錯誤的:
main.cpp: In constructor ‘twoCats::twoCats(cat)’:
main.cpp:24:34: error: no matching function for call to ‘cat::cat()’
main.cpp:24:34: note: candidates are:
main.cpp:9:1: note: cat::cat(int)
main.cpp:9:1: note: candidate expects 1 argument, 0 provided
main.cpp:1:7: note: cat::cat(const cat&)
main.cpp:1:7: note: candidate expects 1 argument, 0 provided
main.cpp:24:34: error: no matching function for call to ‘cat::cat()’
main.cpp:24:34: note: candidates are:
main.cpp:9:1: note: cat::cat(int)
main.cpp:9:1: note: candidate expects 1 argument, 0 provided
main.cpp:1:7: note: cat::cat(const cat&)
main.cpp:1:7: note: candidate expects 1 argument, 0 provided
我不明白以下幾點:
- 爲什麼
twoCats
的構造函數嘗試調用cat
的默認構造函數?當然,它不需要構造一個cat
的實例,因爲當twoCats
被初始化時,它將被傳遞一個cat
的已經初始化的實例,該實例已經通過了int height
參數? - 爲什麼相同的錯誤消息塊顯示兩次?我在Ubuntu 12.04上撥打了
g++ main.cpp
。
首先,你不要在你的構造函數中初始化任何東西。您分配給已經初始化的對象。其次,你只嘗試初始化'firstCat'。 'secondCat'還有什麼用? – chris 2014-09-27 16:58:16
這已被答覆以前的無數次。 – juanchopanza 2014-09-27 16:58:27
@juanchopanza至少你不得不承認OP在第一槍時得到了正確的問題格式;)... – 2014-09-27 17:02:57