這裏是我的代碼:我得到的錯誤:不能聲明變量「a」是抽象類型的「A」
#include <iostream>
using namespace std;
class Base
{
public:
virtual void Sub1() = 0;
virtual void Sub2();
virtual void Sub3();
void Sub4();
};
class A : public Base
{
public:
void Sub2();
void Sub4();
};
class B : public A
{
public:
virtual void Sub1();
void Sub2();
};
class C : public Base
{
public:
virtual void Sub1();
virtual void Sub4();
};
void Base::Sub2()
{
cout << "Hello from Base::Sub2()" << endl;
}
void Base::Sub3()
{
cout << "Hello from Base::Sub3()" << endl;
Sub1(); // DONT MISS THIS CALL IN YOUR ANSWER
}
void Base::Sub4()
{
cout << "Hello from Base::Sub4()" << endl;
}
void A::Sub2()
{
cout << "Hello from A:Sub2()" << endl;
}
void A::Sub4()
{
cout << "Hello from A:Sub4()" << endl;
}
void B::Sub1()
{
cout << "Hello from B:Sub1()" << endl;
}
void B::Sub2()
{
cout << "Hello from B:Sub2()" << endl;
}
void C::Sub1()
{
cout << "Hello from C:Sub1()" << endl;
}
void C::Sub4()
{
cout << "Hello from C:Sub4()" << endl; //error used to say from Sub2
}
void Sub(Base& x)
{
x.Sub1();
x.Sub2();
x.Sub3();
}
void AnotherSub(A& a)
{
a.Sub1();
a.Sub2();
a.Sub4();
}
int main()
{
A a; // wont compile
B b;
C c;
Sub(a);
Sub(b);
Sub(c);
AnotherSub(b);
}
我在與A a;
麻煩,顯然結束Sub(a);
因爲不能被使用,但在最後,它說,「錯誤:不能聲明變量'a'是抽象類型'A'」任何幫助將不勝感激,謝謝。
---另外如果有幫助,輸出不帶A a;作品看起來像:
Hello from B:Sub1()
Hello from B:Sub2()
Hello from Base::Sub3()
Hello from B:Sub1()
Hello from C:Sub1()
Hello from Base::Sub2()
Hello from Base::Sub3()
Hello from C:Sub1()
Hello from B:Sub1()
Hello from B:Sub2()
Hello from A:Sub4()
因爲'A'沒有實現從'Base'繼承的純虛函數'Sub1()'。 – songyuanyao
相關:[虛函數和純虛函數之間的區別](http://stackoverflow.com/q/2652198)它可能有助於更好地理解問題。 –
您應該發佈錯誤消息。 – Galik