【发布时间】:2021-07-19 18:51:06
【问题描述】:
将以下代码作为最低工作示例:
#include <iostream>
class Object_A
{
public:
int attribute_a,attribute_b;
Object_A(int a,int b){
this->attribute_a = a;
this->attribute_b = b;
}
int object_method(){
std::cout << "Hello from Object A: " << std::endl;
return (this->a + this->b);
}
};
class Object_B
{
public:
int attribute_c, attribute_d;
Object_B(int c,int d){
this->attribute_c = c;
this->attribute_d = d;
}
int object_method(){
std::cout << "Hello from Object B" << std::endl;
return (this->c + this->d);
}
};
class Object_Omega
{
public:
Object_A alpha;
Object_B beta;
Object_Omega (Object_A first, Object_B second):
alpha(first),
beta(second)
{}
int foobar(int a){ return a; }
};
void according_to_user_input(bool input,Object_Omega obj)
{
void * either_A_or_B;
if (input){ either_A_or_B = & obj.alpha; }
else { either_A_or_B = & obj.beta; }
/* problem here */
for(int i = 0; i < either_A_or_B->object_method(); i++)
{
std::cout << i << std::endl;
}
}
int main()
{
/* this happens somewhere */
Object_A new_A = Object_A(1,2);
Object_B new_B = Object_B(3,4);
Object_Omega W = Object_Omega(new_A, new_B);
according_to_user_input(true/*false*/, W);
return 0;
}
我希望使用 void 指针(例如,在函数 according_to_user_input 内),但我很难理解正确的方法来做到这一点。 [1]、[2] 也有人问过类似的问题,但在指针指向的值是自定义对象的情况下,我没有设法完成这项工作。
鉴于用户输入,我希望从 A 或从 B 通过 Omega 对象调用 object_method()。不幸的是,我一直在处理的代码具有这种展示行为,而不是对象之间的继承关系,以避免丑陋的 void 类似 C 并且绝对不是类似 C++ 的场景。
提前谢谢你!
【问题讨论】:
-
我不确定您的示例有多具有代表性,以及是否允许您使用 C++11,但通常我会使用从一个通用基类、智能指针(例如
std::shared_ptr)和 @ 继承987654333@ 函数可以完全避免这种情况。如有必要,您可以使用std::static_pointer_cast。 -
和我昨天给的答案here类似。
标签: c++ void-pointers