[英]c++ arithmetic with unknown types:void pointers?
(I want to deal with "void" I am avoid "template class" because it is too much trouble) (我想处理“ void”,我避免使用“ template class”,因为这太麻烦了)
ok establish some ground 好,建立一些基础
int aa=3;
int bb=4;
int cc=0;
int *a, *b, *c;
a = &aa;
b = &bb;
c = &cc;
*c = *a +*b; //yields 7
but I want to do the following: 但我要执行以下操作:
void *va;
void *vb;
void *vc;
va = a;
vb = b;
*c = (int)(*va + *vb); // <-- 3 errors see below
but I get errors: 但是我得到了错误:
error C2100: illegal indirection
error C2100: illegal indirection
error C2110: cannot add two pointers
You can't dereference void
pointer. 您不能取消引用void
指针。
If you want to turn them into int*
you should do that before dereferencing; 如果要将它们转换为int*
,则应在取消引用之前进行;
(*(int*)vc) = (*(int*)va) + (*(int*)vb);
But you better be more specific, what exactly you want to do that you call "the following". 但是您最好更具体一些,确切地说您想做什么就是您所说的“以下”。
You cannot do many operations at all on truly unknown types in C or C++. 您根本无法对C或C ++中真正未知的类型执行很多操作。
You could use Boost Variant to support multiple arithmetic types in one variable, or you could use a union
and basically do what Boost Variant does by discriminating it yourself. 您可以使用Boost Variant在一个变量中支持多种算术类型,也可以使用并union
并基本上通过自己区分来实现Boost Variant的功能。 Or you could build a type hierarchy and have virtual methods to perform the operations you need. 或者,您可以构建类型层次结构并拥有虚拟方法来执行所需的操作。 But you can't perform arithmetic on values whose types have been completely erased . 但是您不能对类型被完全删除的值进行算术。
The void
pointer is a special pointer, it specifically denotes the absence of a type. void
指针是一种特殊的指针,它专门表示没有类型。 These are often used to provide storage to a caller who does know the type and can cast back and forth. 这些通常用于为确实知道类型并且可以来回转换的呼叫者提供存储。
Dereferencing a void*
makes no sense and is, in-fact, invalid syntax, the whole point of dereferencing a pointer is to get the item being pointed to, if you don't specify what you're pointing at, you cant get it. 提领一void*
是没有意义的,并且是在-事实上,无效的语法,解引用指针的全部意义在于获得该项目被指出,如果你不指定哪些你指点,你不能让它。
To "fix" your code you'd need to cast before dereferencing: http://www.ideone.com/eKxxn 要“修复”您的代码,需要在取消引用之前进行强制转换: http : //www.ideone.com/eKxxn
#include <iostream>
int main() {
int ia = 1, ib = 2, ic = -1;
int *a = &ia, *b = &ib, *c = ⁣
void *va, *vb;
va = a;
vb = b;
*c = (int)(*static_cast<int*>(va) + *static_cast<int*>(vb));
std::cout << *c; // Outputs "3"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.