久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

C++ 從基類指針訪問派生類成員

C++ Access derived class member from base class pointer(C++ 從基類指針訪問派生類成員)
本文介紹了C++ 從基類指針訪問派生類成員的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

如果我分配一個 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_intDerived 的一部分,而 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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和簡單指針的區別?)
Difference between const. pointer and reference?(常量之間的區別.指針和引用?)
How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何從指向向量的指針訪問向量的內容?)
Meaning of *amp; and **amp; in C++(*amp; 的含義和**amp;在 C++ 中)
Why can#39;t I do polymorphism with normal variables?(為什么我不能對普通變量進行多態?)
Dereferencing deleted pointers always result in an Access Violation?(取消引用已刪除的指針總是會導致訪問沖突?)
主站蜘蛛池模板: 九九九久久国产免费 | 91精品国产91久久久久久最新 | 香蕉久久av| 中文字幕第一页在线 | 99热首页 | 日韩一区二区在线免费观看 | 欧美日韩一区在线观看 | 在线色网 | 日韩综合一区 | 亚洲免费毛片 | 免费黄色的视频 | 91免费在线视频 | 亚洲精品久久区二区三区蜜桃臀 | 日日摸日日碰夜夜爽亚洲精品蜜乳 | 欧美精品91| 日韩欧美一区二区在线播放 | 久久精品久久精品久久精品 | 欧美日韩精品亚洲 | 国产成人高清视频 | 亚洲色欲色欲www | 人人九九精 | 精品国产一区二区三区久久久四川 | 99色综合 | 99久久精品国产一区二区三区 | 国产高清视频在线 | 久久91精品 | 黄色毛片在线看 | 国产精品大全 | 国产高清在线 | 国产美女h视频 | 久久久久久99| 欧美日高清 | 日韩中文久久 | 国产91丝袜在线播放 | 欧美性网 | 中文字幕在线免费 | 国产成人精品视频 | 亚洲国产欧美日韩 | 久久久精品一区 | 精品国产一区二区国模嫣然 | 四虎在线视频 |