c ++从派生类

时间:2015-10-02 01:35:11

标签: c++ constructor base derived

我正在上C ++课,不幸的是我们正在学习过时的C ++。这个问题是具体的,我不能只谷歌它。谢谢你的回答。

我如何从派生的ctor init-list访问基本私有?我如何从派生的ctor执行块调用函数?

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

city.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为了便于参考;它是我唯一明确的ctor)

City's explicit ctorCity's move ctor中,我收到同样的错误: operator= 未找到重载。同上string::assign,以及其他所有字符串方法。这是怎么回事? string已包含在内。

如果我将protected:放在Point's私有号码前,然后尝试在explicit City ctor初始化列表x { xx }, .. name { nname } {}中初始化它们,则错误说 x不是成员或基类

1 个答案:

答案 0 :(得分:1)

问题是如果 public void methodC{ methodA; try{ methodB; }catch(Exception e) { System.out.println(e.getMessage()); } } 被标记为std::string name,那么您无法分配,因为const当然是非常量的。只需在构造函数列表初始化中初始化它,如std::basic_string<>::operator=

以下是一个例子:

name {other.name}
相关问题