c++传递包含指针的const结构 - 如何移动值?

标签 c++ function pointers struct constants

    typedef struct {
        unsigned int width;
        unsigned int height;
        PBYTE pixels;
    } PBYTEImage;

    void someFunction(const PBYTEImage& inputImage)
    {
        for (unsigned int x = 0; x < inputImage.width*inputImage.height; x++) 
        {
            unsigned char y = *(inputImage.pixels);
->          inputImage.pixels += 1;
        }
    }

Error: expression must be a modifiable value

我是否在修改 PBYTE 的内容?我以为 inputImage.pixels += 1; 只会将指针 PBYTE 前进到下一个值...对吗?

想要什么:

  • 结构的内容不应该被函数修改

  • 函数应该能够读取结构,并在读取其数据时推进指针 PBYTE

我不认为我可以将 struct 中的项目设为 const,因为调用者必须分配它们的值。

最好的方法是什么?

    void someFunction(const PBYTEImage* inputImage)

有同样的效果.. 似乎 const 适用于不允许我修改其指针的结构,包括指针指向的值......

我必须删除 const 吗?有没有办法表明函数不修改数据?

编辑:PBYTE

typedef unsigned char BYTE;   
typedef BYTE near *PBYTE;

minwindef.hwindef.h 中定义

抱歉没有提到

最佳答案

Do I have to drop the const ? Is there no way to show that the function does not modify the data ?

实际上,您的函数确实会更改参数数据,因为您正在递增 inputImage.pixels。 因此,您可能想要存储 inputImage.pixels 并对其进行迭代。

void someFunction(const PBYTEImage& inputImage)
{
    PBYTE pPixels = inputImage.pixels;
    for (unsigned int x = 0; x < inputImage.width*inputImage*height;) 
    {
        unsigned char y = *pPixels;
        pPixels += 1;
    }
}

关于c++传递包含指针的const结构 - 如何移动值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974794/

相关文章:

java - 从子类的子类访问父成员

c++ - 初始化列表中的非常量表达式无法从类型 'unsigned long' 缩小到 'int'

c++ - 通过将最小的数字放在第一位来将两个数组组合成一个

c++ - 我的游戏引擎的Entity-Component-System中的GetComponent <>()函数返回编译器错误C2440

javascript - 名称 : function(){} or function name (){} | ReactJS

function - Lisp-在函数的多个语句中修改局部变量

c - 为什么我的整数数组显示随机值?

c++ - 将字符串指向另一个字符串指针 C++

c++ - GTK+ 如何处理指针?

C++ 候选函数不可行?