访问父类(C ++)中的子成员 [英] Access child members within parent class, C++

查看:325
本文介绍了访问父类(C ++)中的子成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着一种情况,我需要访问父类中的子成员变量。我知道这是违反OO原则,但我必须处理一个场景,其中数百个类从一个继承,并沿着一半他们停止使用一个父变量,并宣布和使用自己的(有需要切换从int到int [],显然是那个没有考虑在父类中应用此更改的人)。


一个选项是有一个虚拟函数来处理它,但这意味着我必须改变在几百个文件/对象中的代码,并测试每一个。因此,我想如果有可能使用一些老学校的C指针魔术来访问这个变量在父方法,这将消除数百个虚拟函数的需要。





基本上这就是我要实现的:

  class Parent 
{
void DoSomething()
{
//这是我需要的
childMember = 0;
}
}

class Child1:Parent
{
int childMember;
}

class Child2:Parent
{
int childMember;
}

请让我知道这是否可能。如果是,我该如何实现。
$ $ $ b其他建议值得欢迎,但请记住,我只想在父类中进行更改。
elves TIA。

解决方案

唯一清洁的方法是使用虚函数方法。 >

如果 Parent 类至少有一个虚函数(不一定 DoSomething

  void DoSomething(){
if(Child1 * child = dynamic_cast< Child1 *>(this)){
child-> childMember = 0;
} else if(Child2 * child = dynamic_cast< Child2 *>(this)){
child-> childMember = 0;
} //等等,如此等等
}

Parent 没有虚函数,那么 dynamic_cast 将无法工作。有至少一个虚函数,即使它只是析构函数。)


I am facing a situation where I need to access child member variables inside the parent class. I know this is against OO principles but I have to deal with a scenario where hundreds of classes are inheriting from one and along the way half of them stopped using one of the parents variable, and declared and used their own (there was need to switch from int to int[] and apparently the person who did that didn't take in consideration to apply this changes in the parent class instead).

One option is to have a virtual function to deal with it, but this means I have to change the code in hundreds of file/objects and test each one of them. Hence I thought if it is possible to use some old school C pointer magic to gain access to this variables inside the parent method, this will eliminate the need of hundreds of virtual functions.

Basically this is what I want to achieve:

class Parent
{
    void DoSomething()
    {
        // This is what I need
        childMember = 0;
    }
}

class Child1 : Parent
{
    int childMember;
}

class Child2 : Parent
{
    int childMember;
}

Please let me know if this is even possible. If yes how do I achieve that.
Other suggestions are welcomed, but keep in mind that I'd like to make changes only in the parent class.
TIA.

解决方案

The only clean way is to use the virtual function approach.

If the Parent class has at least one virtual function (not necessarily DoSomething), there's also a yucky way to do it:

void DoSomething() {
    if (Child1* child = dynamic_cast<Child1*>(this)) {
        child->childMember = 0;
    } else if (Child2* child = dynamic_cast<Child2*>(this)) {
        child->childMember = 0;
    } // and so on, and so forth
}

(If Parent has no virtual functions, then the dynamic_cast won't work. Though, any class designed to be inherited from should have at least one virtual function, even if it's just the destructor.)

这篇关于访问父类(C ++)中的子成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆