[英]c++ usage of delegated ctor from base class in derived class
I'm taking a C++ class, and we're learning outdated C++ unfortunately. 我正在上C ++课程,很不幸,我们正在学习过时的C ++。 This question is specific and I couldn't just Google it.
这个问题很具体,我不能只用谷歌搜索。 Thank you for answering.
感谢您的回答。
How do I / can I access base privates from a derived ctor init-list? 我/如何从派生的ctor初始化列表访问基本私有文件? How do I / can I call a function from a derived ctor execution block?
我/如何从派生的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
for ease of reference; it's the only explicit ctor I have) (
explicit ctor
为便于参考,它是唯一明确的构造函数我有)
In City's explicit ctor
and City's move ctor
, I get the same error: no overload found for operator=
. 在
City's explicit ctor
和City's move ctor
,我得到了相同的错误: 没有发现operator=
重载 。 Ditto with string::assign
, and every other string method. 与
string::assign
和其他所有字符串方法同上。 What's going on? 这是怎么回事?
string
is included. 包含
string
。
If I stick protected:
in front of Point's
privates and then try to initialize them in the explicit City ctor
initialization list x { xx }, .. name { nname } {}
, the error says x is not a member or base class 如果我坚持
protected:
在Point's
私有对象前面,然后尝试在explicit City ctor
初始化列表x { xx }, .. name { nname } {}
初始化它们,则错误表明x不是成员或基类
The problem is that if std::string name
is marked const
, then you cannot assign to it, as std::basic_string<>::operator=
is of course non-const. 问题在于,如果
std::string name
标记为const
,则您无法为其分配值,因为std::basic_string<>::operator=
当然是非const的。 Just initialize it in the constructor list initialization like name {other.name}
只需在构造器列表初始化中将其初始化,例如
name {other.name}
Below is an example: 下面是一个示例:
#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.