【发布时间】:2020-09-23 19:14:02
【问题描述】:
我有一个名为 Base 的基类和一个名为 Derived 的 Base 派生类, 基类指针可以指向派生类对象,也可以访问它的资源,但是这样做会出错。
class Base
{
public:
int a;
};
class Derived : public Base
{
public:
float b;
void DoSomething()
{
cout<<"Derived";
}
};
int main()
{
Base * pBase = new Derived();
pBase->DoSomething();
pBase->a = 5;
pBase->b = 0.2f;
return 0;
}
这给了我一个错误
main.cpp: In function ‘int main()’:
main.cpp:34:25: error: ‘class Base’ has no member named ‘DoSomething’
pBase->DoSomething();
^
main.cpp:36:12: error: ‘class Base’ has no member named ‘b’
pBase->b = 0.2f;
^
如果它太基础,请原谅我,我是 C++ 的初学者
【问题讨论】:
-
如果您使用
Derived作为Base,它会受到Base所知道的限制。Base没有DoSomething所以Base不能使用DoSomething。 -
但是看到这个
Base * pBase = new Derived();我们可以做到这一点。我研究过这是允许的,即基类指针可以存储对其派生类的引用 -
Derivedis-aBase。它知道Base知道的一切,并且可以用作Base。但是Base不知道Derived知道什么。Base*可能指向Derived,也可能指向具有不同功能的AlsoDerived。 Look intovirtualmethods 如果您希望Base中的行为可以由派生自Base的类指定。
标签: c++ pointers inheritance derived-class base-class