我正在上 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 ctor
和 City'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/