c++在派生类中使用来自基类的委托(delegate)ctor

标签 c++ constructor radix derived

我正在上 C++ 类(class),不幸的是我们学习的是过时的 C++。这个问题很具体,我不能只用谷歌搜索。谢谢你的回答。

我如何/可以从派生的 ctor 初始化列表访问基本私有(private)对象?我如何/可以从派生的 ctor 执行 block 中调用函数?

点.h

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 }, {}

城市.h

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 前privates 然后尝试在 explicit City ctor 中初始化它们初始化列表 x { xx }, .. name { nname } {} ,错误提示 x 不是成员或基类

最佳答案

问题是如果std::string name标记为 const ,那么你不能分配给它,因为 std::basic_string<>::operator=当然是非常量。只需在构造函数列表初始化中对其进行初始化,如 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()
{
}

关于c++在派生类中使用来自基类的委托(delegate)ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899263/

相关文章:

Delphi xe2 编码/解码 Base 64

C++ 和 Sqlite DELETE 查询实际上并没有从数据库文件中删除值

c++ - vector 的 vector 的初始化是否可以进行范围构造?

javascript - 为什么在 JavaScript 中函数既是构造函数又是对象?

javascript - 无法弄清楚 JavaScript 的构造函数

c++ - 从 B 转换为基类 A

java - 如何查找远程服务器 URL 的基础或上下文

c++ - 如何从 Arduino 库中读取数组?

c++ - foo2.cpp :9: error: expected primary-expression before '(' token

javascript - 在 Javascript 中设置模块的原型(prototype)