在c++中快速将基对象的所有成员赋值给派生对象
Quickly assign all the members of a base object to a derived object in C++
假设我们有一个基类和一个派生类:
class Base {
string s1;
string s2;
...
string s100; // Hundreds of members
};
class Derived : public Base{
string s101;
};
我想把一个基对象base
赋值给一个派生对象derived
。我知道我们不能仅仅使用运算符"="将基对象赋值给它的派生对象。我的问题是:我们要把所有的成员都一一复印吗?如:
derived.s1 = base.s1;
derived.s2 = base.s2;
...
derived.s100 = base.s100;
是否有更快或更简洁的方法来做到这一点?重载操作符= with返回的基对象?
我想把一个Base对象赋值给一个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;
我知道我们不能仅仅使用操作符"="将基对象赋值给它的派生的对象。
当然可以(在这个问题的上下文中):
static_cast<Base &>(derived)=base;
股票的例子:class Base {};
class Derived : public Base {};
void foo()
{
Derived d;
Base b;
static_cast<Base &>(d)=b;
}
我知道我们不能仅仅使用操作符"="将基对象赋值给它的派生对象
那不是真的。
我们必须一个一个地复制所有成员吗?如:基地。S1 = derived.s1;基地。S2 = derived.s2;…基地。
没有。正如Danh在第一条评论中提到的。
base = derived
就足够了,因为它执行隐式动态上转换(即从指针到派生转换到指针到基)。见http://www.cplusplus.com/doc/tutorial/typecasting/
相关文章:
- 指向设备对象成员的指针
- 访问由unique_ptr传递的对象成员
- 引用对象成员函数的成员函数
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- Lua C API - 从C++分配和使用类的对象成员
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- 类对象成员变量在调用函数时不会更改
- 对象成员变量还是继承
- C++多态性:有没有办法找到对象成员函数的地址?
- 重载对象成员的比较运算符
- 获取未初始化对象成员的地址是否定义良好?
- 在优先级队列被推送到队列后,如何编辑对象成员
- 为什么在这里调用析构函数,以及在调用该对象析构函数后如何调用对象成员函数?
- 通过 std::bind 从对象成员检索值
- 保留对象成员变量的本地副本
- 有没有办法为静态对象成员定义一个符合开关标准的常量?
- 没有默认构造函数的对象成员的 wig setter
- 对象成员数组C++默认初始化
- 如何在数组中添加对象成员
- 使用聚合创建和关联两个不同的对象成员