![](/img/trans.png)
[英]How to delay the initialisation of a member in a C++ base class until the ctor of derived class is executed?
[英]c++ usage of delegated ctor from base class in derived class
我正在上C ++課程,很不幸,我們正在學習過時的C ++。 這個問題很具體,我不能只用谷歌搜索。 感謝您的回答。
我/如何從派生的ctor初始化列表訪問基本私有文件? 我/如何從派生的ctor執行塊調用函數?
點
class Point {
const double x;
const double y;
public:
Point () = delete;
Point ( Point && other ) : x { other.x }, y { other.y } {}
explicit Point ( double xx, double yy) : x { xx }, y { yy }, {}
城市
class City : public Point {
const std::string name;
public:
City () = delete;
City ( City && other )
: Point ( std::forward < City > ( other ) ) { name = other.name; }
// is other scrapped by the time I try to get the name?
explicit City ( double xx, double yy, std::string nname )
: Point ( xx, yy ) { name = nname; }
( explicit ctor
為便於參考,它是唯一明確的構造函數我有)
在City's explicit ctor
和City's move ctor
,我得到了相同的錯誤: 沒有發現operator=
重載 。 與string::assign
和其他所有字符串方法同上。 這是怎么回事? 包含string
。
如果我堅持protected:
在Point's
私有對象前面,然后嘗試在explicit City ctor
初始化列表x { xx }, .. name { nname } {}
初始化它們,則錯誤表明x不是成員或基類
問題在於,如果std::string name
標記為const
,則您無法為其分配值,因為std::basic_string<>::operator=
當然是非const的。 只需在構造器列表初始化中將其初始化,例如name {other.name}
下面是一個示例:
#include <iostream>
class Point {
const double x;
const double y;
public:
Point () = delete;
Point ( Point && other ) : x { other.x }, y { other.y } {}
explicit Point ( double xx, double yy) : x { xx }, y { yy } {}
};
class City : public Point {
const std::string name;
public:
City () = delete;
City ( City && other )
: Point ( std::forward < City > ( other ) ) , name {other.name}{}
// is other scrapped by the time I try to get the name?
explicit City ( double xx, double yy, std::string nname )
: Point ( xx, yy ), name{nname}{}
};
int main()
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.