![](/img/trans.png)
[英]Base class on the initialisation list of a derived class' copy constructor (C++)
[英]C++ Copy Constructor for a Derived Class
所以我有這個具有三個父函數的類,或者換句話說,它是從其他三個類派生的。
我正在嘗試制作一個復制構造函數,這就是我所擁有的:
// Copy constructor
extPersonType (extPersonType &obj) : addressType(obj), personType(obj), dataType(obj)
{
cout << "Copy constructor active." << endl;
phone = obj.phone;
ident = obj.ident;
}
這是我的其他三個類的復制構造函數。
// copy constructor
addressType(extPersonType &obj)
{
street = obj.street;
city = obj.city;
state = obj.state;
zipcode = obj.zipcode;
}
// copy constructor
personType(extPersonType &obj)
{
firstname = obj.firstname;
lastname = obj.lastname;
}
// copy constructor
dataType(extPersonType &obj)
{
day = obj.day;
month = obj.month;
year = obj.year;
}
請記住,它們每個都有自己的頭文件和 cpp 文件。 雖然在這種情況下我使用了內聯函數定義。
然而這是我得到的錯誤:
[traine@joker Assignment2]$ make
g++ ExtPerson.cpp -c
In file included from ExtPerson.h:5:0,
from ExtPerson.cpp:3:
Data.h:19:26: error: expected ‘)’ before ‘&’ token
dataType(extPersonType &obj)
^
In file included from ExtPerson.h:6:0,
from ExtPerson.cpp:3:
Person.h:18:28: error: expected ‘)’ before ‘&’ token
personType(extPersonType &obj)
^
In file included from ExtPerson.h:7:0,
from ExtPerson.cpp:3:
Address.h:20:29: error: expected ‘)’ before ‘&’ token
addressType(extPersonType &obj)
^
make: *** [ExtPerson.o] Error 1
有誰知道我做錯了什么? 我只是對如何在派生類中創建復制構造函數以及如何在其他類中調用其他復制構造函數感到困惑。 任何幫助將不勝感激,謝謝。
您可能需要添加前向聲明,因為派生類在您聲明基類時尚未聲明。
class extPersonType;
但這不是必須的。 為什么不按照正常模式聲明基本構造函數? 即接受與類相同類型的參數。 這將工作正常並且不依賴於派生類。
personType(const PersonType &obj)
: firstname(obj.firstname)
, lastname(obj.lastname)
{
}
順便說一句,當您使用初始化列表時,它更有效並且表明您了解C++。 它將避免調用默認構造函數,然后調用賦值運算符。
https://en.cppreference.com/w/cpp/language/initializer_list
但是,使用派生將不相關的對象放在一起仍然是一個糟糕的設計。 地址不符合與某人的 IS-A 關系。 所以它沒有多大意義, extPersonType
從派生addressType
。
當您的extPersonType
類具有addressType
成員時,您應該使用包含。
class extPersonType : public personType
{
addressType address;
dataType birth_date;
};
一次從 3 個類派生的唯一原因是懶惰。 隨着類的增長,您最初將節省的幾秒鍾將使您的代碼更難維護。 並且在某些時候,您可能需要支持多個地址或日期,例如招聘日期,如果在這種情況下,隨着變量在許多地方使用,您將不得不對代碼進行更多更改。 您將浪費最初節省的所有時間以及更多。
順便說一句,在代碼中拼錯單詞是個壞主意。 正確的拼寫是日期而不是數據,因為我們可以很容易地看出它是來自成員的日期而不是任意數據。
順便說一句,閱讀有關設計和編碼的好書可能是個好主意,因為這是每個程序員都應該掌握的非常基本的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.