基本上,我只是想知道为什么这行不通。
//main.cpp
#include "testHeader.h"
int main(int argc,char** argv)
{
Car *car1;
car1 = new Ford;
car1->foo();
return 0;
}
//testHeader.h
class Car {
public:
Car();
virtual void foo();
};
//Ford.cpp
#include "testHeader.h"
#include <iostream>
class Ford : Car {
public:
Ford();
void Foo() { std::cout << "I am a Ford";};
};
我得到 2 个错误;
error: expected type-specifier before 'Ford'
car1 = new Ford;
^
error: expected ';' before 'Ford'
我已经用谷歌搜索了一个小时左右,但没能找到任何有用的东西。
最佳答案
您对 Ford
的定义应该在您在 main 中
。否则 #include
的头文件中(可能是 Ford.h
)。 cppmain.cpp
甚至看不到它的存在。
确保将包含保护添加到 header 中,否则以后可能会遇到麻烦。
您还需要将 Car
的继承公开:
class Ford : public Car {
关于c++ - 尝试在基类之外创建派生类的实例时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919409/