取消引用指向对象的空指针



给定以下代码作为最低限度的工作示例:

#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],但在指针指向的值是自定义对象的情况下,我没能做到这一点。

给定用户输入,我希望通过Omega对象从A或从B调用object_method()。不幸的是,我一直在编写的代码中展示了这种行为,而不是对象之间的继承关系,以避免出现丑陋的类似voidC的场景,当然也不是类似C++的场景。

提前谢谢!

不能间接通过指向void的指针。并且不需要指向CCD_ 9的指针。

最简单的解决方案是:

int number = 1;
std::cout << input
? obj.alpha.object_method(number)
: obj.beta.object_method(number);

对于编辑后的问题:上面的仍然有效,但您可以使用函数模板来消除复杂代码的重复。下面是一个使用lambda:的例子

auto do_stuff = [](auto& either_A_or_B) {
for(int i = 0; i < either_A_or_B.object_method(); i++)
{
std::cout << i << std::endl;
}
};
input
? do_stuff(obj.alpha)
: do_stuff(obj.beta);

p.S.避免使用C样式的强制转换。

这对void*来说不是一个好用,如果像您所评论的那样,您不能利用继承,并且实际问题不仅仅是控制台输出,那么您仍然可以使用函数模板使其通用

template <class T>
void according_to_user_input(T &obj)
{
std::cout << obj.object_method();
}

并像这样使用

if (input)
according_to_user_input<Object_A>(W.alpha);
else
according_to_user_input<Object_B>(W.beta);

相关内容

最新更新