我正在构建一个 DirectX 游戏,我在其中的 Debug 类中定义了一个 Debug::Log 静态函数。这只是在输出/控制台上打印传递参数的值。 我想实现一个函数,我可以将一个起始指针传递给数组(我想打印),并打印数组中的所有元素。但是,我想让函数根据传递的参数类型灵活变化。所以,我正在做这样的事情..
static void DebugArray(void* pointerToArray) {
std::stringstream ss;
ss << "\n";
void *i = pointerToArray;
int k = 0;
while(i) {
ss << i; //This is how I am storing the array's elements
i++; //Error in VS 2012 expression must be a pointer to a complete object type
}
print(ss.str());
}
这是完成预期工作的有效方式吗?我应该如何处理这个问题?有什么建议
最佳答案
需要在编译时知道类型,因此您需要使用模板。
template <class T>
static void DebugArray(T* pointerToArray) {
std::stringstream ss;
ss << "\n";
T *i = pointerToArray;
int k = 0;
while(i) {
ss << *i; //This is how I am storing the array's elements
i++; //Error in VS 2012 expression must be a pointer to a complete object type
}
print(ss.str());
}
关于c++ - 使用 void 指针在 C++ 中打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23176658/