c++ - 使用 void 指针在 C++ 中打印数组

标签 c++ arrays pointers void-pointers

我正在构建一个 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/

相关文章:

c - 如何在函数中使用 realloc() 并访问值?

c - 如何知道我的代码中存在段错误?

c - 将指针数组作为参数传递给 C 中的函数

c++ - 虚拟调度实现细节

c++ - 制作 Vista/7 User Frame 控件? (WinAPI)

java - 为什么java不支持像C++这样的引用传递

Objective-C:一组 UIButtons

javascript - 为什么这里数组中的多重赋值会这样呢?

java - 在java中将int[]二进制数组转换为图像。

c++ - Qt QUdpSocket : readyRead() signal and corresponding slot not working as supposed