[英]dereferencing void pointers to objects
給定以下代碼作為最低工作示例:
#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
指針(例如,在 function 中according_to_user_input
_to_user_input ),但我很難理解正確的方法來做到這一點。 已經提出了類似的問題[1] , [2]但在從指針指向的值是自定義對象的情況下,我沒有設法完成這項工作。
鑒於用戶輸入,我希望通過Omega
object 從A
或B
調用object_method()
。 不幸的是,我一直在處理的代碼按原樣展示了這種行為,而不是作為對象之間的 inheritance 關系,以避免丑陋的void
C-like 並且絕對不是 C++ -like 場景。
先感謝您!
您不能通過指向void
的指針間接。 並且不需要指向void
的指針。
最簡單的解決方案是這樣的:
int number = 1;
std::cout << input
? obj.alpha.object_method(number)
: obj.beta.object_method(number);
對於已編輯的問題:上述方法仍然有效,但您可以使用 function 模板擺脫復雜代碼的重復。 這是使用 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);
PS 避免使用 C 風格的強制轉換。
這不是void*
的好用處,如果像您評論的那樣,您不能使用 inheritance 並且實際問題不僅僅是控制台 output,那么您仍然可以使用 ZC1C425264E68384F1AB450 模板使其通用
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.