問題描述
如果我分配一個 Derived
類的對象(具有 Base
的基類),并將指向該對象的指針存儲在指向基類的變量中類,如何訪問 Derived
類的成員?
If I allocate an object of a class Derived
(with a base class of Base
), and store a pointer to that object in a variable that points to the base class, how can I access the members of the Derived
class?
這是一個例子:
class Base
{
public:
int base_int;
};
class Derived : public Base
{
public:
int derived_int;
};
Base* basepointer = new Derived();
basepointer-> //Access derived_int here, is it possible? If so, then how?
推薦答案
不,您不能訪問 derived_int
因為 derived_int
是 Derived
的一部分,而 basepointer
是指向 Base
的指針.
No, you cannot access derived_int
because derived_int
is part of Derived
, while basepointer
is a pointer to Base
.
你可以反過來做:
Derived* derivedpointer = new Derived;
derivedpointer->base_int; // You can access this just fine
派生類繼承基類的成員,而不是相反.
Derived classes inherit the members of the base class, not the other way around.
但是,如果您的 basepointer
指向 Derived
的實例,那么您可以通過強制轉換訪問它:
However, if your basepointer
was pointing to an instance of Derived
then you could access it through a cast:
Base* basepointer = new Derived;
static_cast<Derived*>(basepointer)->derived_int; // Can now access, because we have a derived pointer
請注意,您需要先將繼承更改為 public
:
Note that you'll need to change your inheritance to public
first:
class Derived : public Base
這篇關于C++ 從基類指針訪問派生類成員的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!