[英]accessing data member through composition
I have a struct obj in my base class.我的基类中有一个 struct obj 。 I don't know how to access the data members of the struct through Derv1 class (Derived from the base class).
我不知道如何通过 Derv1 类(派生自基类)访问结构体的数据成员。 I tried making both Base and Derv1 a friend of struct - it still tells me ' data member is private' (its private in Base only).
我尝试让 Base 和 Derv1 成为 struct 的朋友 - 它仍然告诉我“数据成员是私有的”(它仅在 Base 中是私有的)。
example :例子 :
struct A{
public :
int total;
//some stuff
};
class MyClass{ // [Base] class
private:
A var1;
};
class Derv1{
private:
//some stuff
public void display_var1(Derv1 x){
return x.var1.total;
} // trying to return the value of A.total
};
I hope this makes sense so that you can help me out .. Thank You kindly,我希望这是有道理的,以便您可以帮助我......谢谢你,
i think you must extend your Derv1 class into the Base class:我认为您必须将您的 Derv1 类扩展到 Base 类中:
class Derv1: public MyClass{
to inherit the members of the base class继承基类的成员
First, you have to make sure that Derv
derives from MyClass
.首先,您必须确保
Derv
派生自MyClass
。
class Derv1 : public MyClass { ... };
and then, you will need to figure out the best way to display the variable.然后,您需要找出显示变量的最佳方式。
My suggestion:我的建议:
virtual
member function in the base class.virtual
成员函数。class MyClass { // [Base] class
public:
virtual void display() const
{
// Display var1 anyway you wish to.
}
private:
A var1;
};
class Derv1 : public MyClass {
public:
virtual void display() const
{
// Call the base class implementation first
MyClass::display():
// Display anything else that corresponds to this class
}
private:
//some stuff
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.