20

我有一个 C++ 程序:

struct arguments
{
  int a, b, c;  
  arguments(): a(3), b(6), c(9) {}
};

class test_class{
  public:

    void *member_func(void *args){
      arguments vars = (arguments *) (*args); //error: void is not a 
                                              //pointer-to-object type

      std::cout << "\n" << vars.a << "\t" << vars.b << "\t" << vars.c << "\n";
    }
};

编译时会抛出错误:

error: ‘void*’ is not a pointer-to-object type

有人可以解释我做错了什么来产生这个错误吗?

4

6 回答 6

28

void *在将其转换为具体类型之前取消引用。你需要反过来做:

arguments vars = *(arguments *) (args);

这个顺序很重要,因为编译器不知道如何应用*args这是 avoid *并且不能被取消引用)。你(arguments *)告诉它该做什么,但为时已晚,因为取消引用已经发生。

于 2011-10-31T03:35:10.060 回答
8

重现上述错误的裸骨示例:

#include <iostream>
using namespace std;
int main() {
  int myint = 9;             //good
  void *pointer_to_void;     //good
  pointer_to_void = &myint;  //good

  cout << *pointer_to_void;  //error: 'void*' is not a pointer-to-object type
}

上面的代码是错误的,因为它试图取消引用指向 void 的指针。这是不允许的。

现在运行下面的下一个代码,如果您理解为什么下面的代码运行而上面的代码没有运行,那么您将更好地理解幕后发生的事情。

#include <iostream>
using namespace std;
int main() {
    int myint = 9;
    void *pointer_to_void;
    int *pointer_to_int; 
    pointer_to_void = &myint;
    pointer_to_int = (int *) pointer_to_void;

    cout << *pointer_to_int;   //prints '9'
    return 0;
}
于 2014-05-27T01:38:06.093 回答
5

你有*错误的地方。所以你正在尝试取消引用void*. 试试这个:

arguments vars = *(arguments *) (args);
std::cout << "\n" << vars.a << "\t" << vars.b << "\t" << vars.c << "\n";

或者,您可以这样做:(这也避免了复制构造函数 - 如评论中所述)

arguments *vars = (arguments *) (args);
std::cout << "\n" << vars->a << "\t" << vars->b << "\t" << vars->c << "\n";
于 2011-10-31T03:33:26.277 回答
2

bdonlan 所说的问题是“void*在转换之前取消引用”。

我认为这个例子会有所帮助:

#include <iostream>

using namespace std;

int main()
{



   void *sad;
   int s = 23;
   float d = 5.8;

   sad = &s;
   cout << *(int*) sad;//outputs 23//wrong: cout << *sad ;//wrong: cout << (int*) *sad;



   sad = &d;
   cout << *(float *) sad;//outputs 5.8//wrong: cout << *sad ;//wrong: cout << (float*) *sad;

   return 0;
}
于 2015-06-09T15:43:17.237 回答
0

*args 表示“对象(值)args 指向”。因此,它不能被转换为指向对象(参数)的指针。这就是为什么它给出错误

于 2011-10-31T04:57:41.597 回答
0

上面的问题是您试图尊重 C 或 C++ 中不允许的 void 指针。

但是,这仍然有效:

#include <iostream>
using namespace std;
int main()
{
    int b=10;
    void *a=&b;
    int *ptr=(int*)a;
    cout<<*ptr;;
} 

在将 void 指针转换为 int* 指针之后,我们可以尊重 int* 指针。

于 2019-06-21T13:23:58.217 回答