이것은 인터뷰 질문이었습니다. a = b;
완벽하게 잘하는 동안,기본 클래스에 대한 할당이 유효하지만 파생 클래스에 대한 컴파일 오류가 할당되는 이유는 무엇입니까?
struct A {};
struct B : A {};
A a;
B b;
a = b;
b = a;
왜 b = a;
이 오류가 발생 않습니다 다음 고려? 당신의 예에서
struct A {int someInt;};
struct B : A {int anotherInt};
A a;
B b;
/* Compiler thinks: B inherits from A, so I'm going to create
a new A from b, stripping B-specific fields. Then, I assign it to a.
Let's do this!
*/
a = b;
/* Compiler thinks: I'm missing some information here! If I create a new B
from a, what do I put in b.anotherInt?
Let's not do this!
*/
b = a;
:
무엇이 오류입니까? – MGZero
사실 그건 아주 좋은 질문입니다. 첫 번째 진술이 효과가있는 이유는 즉시 명백하지 않습니다. –
구조체가 클래스처럼 동작한다고 가정합니다.이 구조체는 모든 고유 한 'B'구조체 항목을 잘라 내고 모든 'a'를 복사합니다. – DanTheMan