在 C++ 中快速将基对象的所有成员分配给派生对象
Quickly assign all the members of a base object to a derived object in C++
假设我们有一个基础 class 和一个衍生 class:
class Base {
string s1;
string s2;
...
string s100; // Hundreds of members
};
class Derived : public Base{
string s101;
};
我想将 Base 对象 base
分配给 Derived 对象 derived
。我知道我们不能只使用运算符“=”将基对象分配给它的派生对象。
我的问题是:我们是否必须将所有成员逐一复制?喜欢:
derived.s1 = base.s1;
derived.s2 = base.s2;
...
derived.s100 = base.s100;
有没有更快或更简洁的方法来做到这一点?重载 operator= 与
返回的基础对象?
I know we can't just use operator "=" to assign a base object to its
derived object.
当然可以(在这个问题的上下文中):
static_cast<Base &>(derived)=base;
库存示例:
class Base {};
class Derived : public Base {};
void foo()
{
Derived d;
Base b;
static_cast<Base &>(d)=b;
}
I know we can't just use operator "=" to assign a base object to its derived object
这不是真的。
Do we have to make copies of all the members one by one? Like:
base.s1 = derived.s1;
base.s2 = derived.s2;
...
base.s100 = derived.s100;
不是真的。正如 Danh 在第一条评论中提到的。
base = derived
就足够了,因为它执行隐式动态向上转换(即从派生指针转换为基指针)。参见 http://www.cplusplus.com/doc/tutorial/typecasting/
I want to assign a Base object base to a Derived object derived.
为其提供重载operator=
:
class Derived : public Base {
Derived& operator=(const Base& b) {
Base::operator=(b); // call operator= of Base
s101 = something; // set sth to s101 if necessary
return *this;
}
};
那你可以
Base b;
// ...
Derived d;
// ...
d = b;
假设我们有一个基础 class 和一个衍生 class:
class Base {
string s1;
string s2;
...
string s100; // Hundreds of members
};
class Derived : public Base{
string s101;
};
我想将 Base 对象 base
分配给 Derived 对象 derived
。我知道我们不能只使用运算符“=”将基对象分配给它的派生对象。
我的问题是:我们是否必须将所有成员逐一复制?喜欢:
derived.s1 = base.s1;
derived.s2 = base.s2;
...
derived.s100 = base.s100;
有没有更快或更简洁的方法来做到这一点?重载 operator= 与 返回的基础对象?
I know we can't just use operator "=" to assign a base object to its derived object.
当然可以(在这个问题的上下文中):
static_cast<Base &>(derived)=base;
库存示例:
class Base {};
class Derived : public Base {};
void foo()
{
Derived d;
Base b;
static_cast<Base &>(d)=b;
}
I know we can't just use operator "=" to assign a base object to its derived object
这不是真的。
Do we have to make copies of all the members one by one? Like: base.s1 = derived.s1; base.s2 = derived.s2; ... base.s100 = derived.s100;
不是真的。正如 Danh 在第一条评论中提到的。
base = derived
就足够了,因为它执行隐式动态向上转换(即从派生指针转换为基指针)。参见 http://www.cplusplus.com/doc/tutorial/typecasting/
I want to assign a Base object base to a Derived object derived.
为其提供重载operator=
:
class Derived : public Base {
Derived& operator=(const Base& b) {
Base::operator=(b); // call operator= of Base
s101 = something; // set sth to s101 if necessary
return *this;
}
};
那你可以
Base b;
// ...
Derived d;
// ...
d = b;