【发布时间】:2017-12-20 09:20:08
【问题描述】:
我在这里有点困惑。我在主窗口下有一堆类。一个是基类:DocumentViewer。在此之下,我们有多个子类,如PDFViewer、RichTextViewer、DocumentViewer、ImageViewer 等。
属性 Borders 是基类的一部分,即DocumentViewer。 ImageViewer 具有 AspectRatio 属性。但是当我继承基类时,我可以访问派生类中的 Borders 并相应地用于我的ImageViewer 类吗?
或者我也需要为ImageViewer 类创建相同的方法?
class DocumentViewer : public MainWindow
{
private: bool Borders;
public: bool GetBorders();
void PutBorders(...);
}
....
....
class ImageViewer : public DocumentViewer
{
private: bool AspectRatio;
public: bool GetAspectRatio();
void PutAspectRatio(...);
}
【问题讨论】:
-
如果成员变量
Borders在基类的protected部分中,那么可以从子类访问它。这是继承的要点之一,成员变量也会被继承。 -
请提供minimal reproducible example。标题要求相反:从基类访问派生类成员,而在问题中您想访问派生中的基类成员
-
@tobi303 是的,我更正了标题。将尝试发布示例代码..
-
@HansPassant 好吧,它是这样定义的,现在该属性对于应该像你说的那样做的图像是不可访问的!现在有什么办法或者我需要复制属性吗?
-
@Someprogrammerdude 其实是在私人版块,我已经贴了示例代码,请看一下
标签: c++ inheritance