2012-05-11 2 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()과 같이 파생 클래스 개체에 기본 클래스 개체를 할당하면 컴파일 오류가 발생합니다.

역순이 허용됩니다. 즉, 파생 클래스 객체를 Base 클래스 객체에 할당 할 수 있지만 파생 클래스 객체의 멤버를 조각으로 나눌 수 있습니다. 이 현상을 개체 조각화이라고합니다.

0

일부 C 해킹을 사용할 수 있지만 좋지 않습니다. 가장 좋은 방법은 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; 
    } 

}; 
관련 문제