簡體   English   中英

快速將基礎對象的所有成員分配給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;

有沒有更快或更簡潔的方法來做到這一點? 用返回的基礎對象重載operator =?

我知道我們不能只使用運算符“ =”將基礎對象分配給它的派生對象。

當然可以(在這個問題的范圍內):

static_cast<Base &>(derived)=base;

股票示例:

class Base {};

class Derived : public Base {};

void foo()
{
    Derived d;
    Base b;

    static_cast<Base &>(d)=b;
}

我想將基礎對象庫分配給派生的派生對象。

為此提供一個重載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;

我知道我們不能只使用運算符“ =”將基礎對象分配給其派生對象

這不是真的。

我們是否必須一張一張地復制所有成員? 像:base.s1 =派生的.s1; base.s2 =派生的s2; ... base.s100 =派生的s100;

並不是的。 正如Danh在第一條評論中所述。

base = derived 

足夠了,因為它執行隱式動態轉換(即從指針到派生轉換為指針到基址)。 參見http://www.cplusplus.com/doc/tutorial/typecasting/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM