Các mã sau đây:Nhiều thừa kế và tinh khiết chức năng ảo
struct interface_base
{
virtual void foo() = 0;
};
struct interface : public interface_base
{
virtual void bar() = 0;
};
struct implementation_base : public interface_base
{
void foo();
};
struct implementation : public implementation_base, public interface
{
void bar();
};
int main()
{
implementation x;
}
thất bại trong việc biên dịch với các lỗi sau đây:
test.cpp: In function 'int main()':
test.cpp:23:20: error: cannot declare variable 'x' to be of abstract type 'implementation'
test.cpp:16:8: note: because the following virtual functions are pure within 'implementation':
test.cpp:3:18: note: virtual void interface_base::foo()
tôi đã chơi đùa với nó và tìm ra rằng làm cho 'giao diện - > interface_base 'và' implementation_base -> interface_base 'thừa kế ảo, khắc phục sự cố, nhưng tôi không hiểu tại sao. Ai đó có thể giải thích chuyện gì đang diễn ra không?
p.s. Tôi bỏ qua các destructors ảo nhằm mục đích làm cho đoạn mã ngắn hơn. Xin vui lòng không cho tôi biết để đưa chúng vào, tôi đã biết :)
cũng xem: http://stackoverflow.com/questions/457609/diamond-inheritance-and-pure-virtual-functions – bdonlan