簡體   English   中英

派生類中基類委派的ctor的c ++使用

[英]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 ctorCity'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM