简体   繁体   English

指针函数从const函数指向的对象的调用运算符

[英]call operator of the object that a pointer argument is pointing to from a const function

define operator 定义运算符

    RGBAPixel * operator()(size_t x, size_t y);
    RGBAPixel const * operator()(size_t x, size_t y) const;

How should I call it in a const function? 我应该如何在const函数中调用它? (that png on the bottom) (底部的png)

PNG Quadtree::decompress() const
{
    PNG * png = new PNG((size_t) res, (size_t) res);
    decompressHelper(png,0,0,res/2,root);
    return * png;
}

void Quadtree::decompressHelper(PNG * png, int x, int y, int setresolution, QuadtreeNode * subRoot) const
{
    if (subRoot->nwChild == NULL) {
        png((size_t) x, (size_t) y) = subRoot->element;

Just define the operator overload as const as well: 只需将运算符重载也定义为const即可:

RGBAPixel * operator()(size_t x, size_t y) const;
                                           ^~~~~

Since you're passing by pointer, you should dereference it before calling (don't forget to dereference): 由于要通过指针传递,因此应在调用之前取消引用它(不要忘记取消引用):

*(*png)((size_t) x, (size_t) y) = subRoot->element;
 ^^   ^

It's not really a function pointer, but a pointer to a class object that can be used as a function. 它实际上不是函数指针,而是指向可用作函数的类对象的指针。 That's a subtle difference, though. 不过,这是一个微妙的区别。

I also recommend changing this function to prevent a potential memory leak: 我还建议更改此功能以防止潜在的内存泄漏:

PNG Quadtree::decompress() const
{
    PNG png((size_t) res, (size_t) res);
    decompressHelper(&png, 0, 0, res/2, root);
    return png;
}

You're not delete -ing what you've allocated with new . 您不会delete使用new分配的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM