【发布时间】:2018-09-24 18:49:27
【问题描述】:
假设我有以下情况:
class NamedObject{
public:
NamedObject(const std::string &name):name_{std::move(name)}{}
private:
const std::string name_;
}
class Person: public NamedObject{
public:
Person(const std::string &name, int age): NamedObject(name), age_{age}{}
private:
int age_;
}
我想创建一个“复制构造函数”,在其中复制来自Person 的所有成员,但更改名称(无论出于何种原因)。
class Person: public NamedObject{
public:
Person(const std::string &name, int age): NamedObject(name), age_{age}{}
Person(const std::string &newName, const Person &other): NamedObject(name){
age_ = other.age;
}
private:
int age_;
}
现在假设我不仅有一个像age 这样的属性,而且还有许多属性,并且它们在开发过程中发生了很大变化。是否可以轻松地创建像 Person(const std::string &newName, const Person &other) 这样的函数,而无需手动复制像 age_ = other.age; 这样的所有属性。这个想法是,在开发过程中,如果我添加一个新属性,我不必总是记得更改这个构造函数。
请注意,我不能简单地更改名称,因为它是 const。
【问题讨论】:
-
不要让它成为常量。
-
你可以有一个虚函数
getName(),还有一个额外的string Person::nameReplacement,在getName中你可以返回Person::nameReplacement或者NamedObject::name_。 -
除此之外,您使用
std::move不正确。 -
对
std::move错误感到抱歉...我知道。 -
作为设计决策,您不需要创建成员变量
const,因为它实际上不具有您在 C++ 中想要的不变性语义。相反,只需将其设为私有的,使用公共 getter 而没有 setter,它实际上是不可变的。
标签: c++ inheritance copy-constructor derived-class