2016-09-26 66 views
2

假设我们有一个基类和一个派生类:快速基础对象的所有成员分配给派生对象在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; 

有没有更快或更简洁的方法来做到这一点?过载操作符= 返回的基础对象?

+1

基地=衍生? – Danh

+0

派生对象不在那里,我当时只有一个基础对象作为数据源。我想创建一个新的派生对象,分配它的成员并将其放入一个容器中,比如地图。 –

+1

那你为什么写'base.s1 = derived.s1' – Danh

回答

2

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; 
2

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; 
} 
+0

谢谢,我会试试这个static_cast。然而,即使在这种情况下,这是一个很好的做法吗? –

+0

@ M.M - 不符合gcc 6.1.1:“t.C:12:4:错误:不匹配'operator ='(操作数类型是'Derived'和'Base')” –

+0

@SamVarshavchik不够公平 –

0

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/

相关问题