2012-05-11 18 views
1
class Base{ 
public: 
float a,b; 
}; 

class Derived:public Base{ 
public: 
int someInteger, otherInt; 

void assignNthElement(vector<Base> &myArray,int i){ 
this=myArray[i-1];//??? How ??? 
} 

void simpleMethodOfAssigningNthElement(vector<Base>&myArray,int i){ 
a=myArray[i-1].a; 
b=myArray[i-1].b; 
} 


}; 

如何從myArray直接複製描述派生類中的基類的值? 也許最好像在「simpleMethodOfAssigningNthElement」中做的那樣做? 哪個更快?如何通過複製,通過派生類中的方法來設置基類字段?

+0

謝謝大家的幫助:) – Opeww

回答

1

您無法按照您在assignNthElement中嘗試的方式進行操作,因此只需要執行simpleMethodOfAssigningNthElement

1

您不能將基類對象分配給派生類對象,如assignNthElement()中那樣會給您一個編譯錯誤。

請注意,相反是允許的,即:您可以將派生類對象分配給基類對象,但最終會分割派生類對象的成員。該現象被稱爲對象切片

0

你可以使用一些C-hacks,但它是不好的方法。最好的方法是simpleMethodOfAssigningNthElement。 如果你想要你可以重載operator=Derived類。

class Base{ 
public: 
float a,b; 
}; 

class Derived : public Base{ 
public: 
    int someInteger, otherInt; 

    void assignNthElement(vector<Base> &myArray,int i){ 
     this = myArray[i-1];// It's OK now 
    } 

    const Derived & operator=(const Base &base){ 
     a=base.a; 
     b=base.b; 
    } 

}; 
相關問題