我有一个名为 classA.h 的文件,如下所示
#include <iostream>
using namespace std;
class A
{
public:
virtual void doSomething();
};
void A::doSomething()
{
cout << "inside A" << endl;
}
然后我有一个 ClassB.cpp 如下所示
#include "classA.h"
class B : public A
{
public:
void doSomething();
};
void B::doSomething()
{
cout << "class B" << endl;
}
然后我有classC.cpp,如下所示
#include <iostream>
#include "classA.h"
using namespace std;
class C : public B
{
public:
void doSomething();
};
void C::doSomething()
{
cout << "classC" << endl;
}
int main()
{
A * a =new C();
a->doSomething();
return 0;
}
当我如下所示编译时,我得到错误
g++ -Wall classB.cpp classC.cpp -o classC
classC.cpp:7: error: expected class-name before '{' token
classC.cpp: In function 'int main()':
classC.cpp:21: error: cannot convert 'C*' to 'A*' in initialization
既然 C 继承自 B,而 B 继承自 A,为什么我不能说A * a = new C();