[英]copy constructor of base and derived classes
我有這兩個班
///////////BASE CLASS
class Base{
public:
Base(int = 0);
~Base();
Base(Base&);
Base(Derived&); ////<-may be problem here?, note: I tried without this function
int valueOfBase();
protected:
int protectedData;
private:
int baseData;
};
/////////////DERIVED CLASS
class Derived: public Base{
public:
Derived(int);
//Derived(Derived&);
~Derived();
private:
int derivedData;
};
and here my main
int main(){
Base base(1);
Derived derived = base;
return 0;
}
我讀過如果我的派生類沒有副本c'tor copy c'tor of the base will be called
但每次我收到conversion from Base to non-scalar type Derived requested
誰是錯的? 我的編譯器或我的書,或者我剛剛被誤解了? 提前致謝
只是一個提示。
以下代碼是否會出現相同的錯誤?
class base{};
class derived: public base{};
int main()
{
derived d= base();
}
是? 為什么? 因為沒有從基類到派生類的轉換。 如果希望編譯代碼,則應定義此轉換。
如何將它添加到派生類?
derived(const base &b){}
有道理,對吧?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.