对象本身作为参数的对象上的 C++ 调用方法

标签 c++ oop methods openframeworks

例如,在 Python 中,您可以调用 array.sort(),它将对调用它的数组进行排序。但是,我现在有以下代码片段

void drawClickableRectangle(ClickableRectangle recto){
        ofSetHexColor(0xffffff);             // just some syntax from the library I'm using
        ofFill();
        ofDrawRectangle(recto.xpos, recto.ypos, recto.width, recto.height);
    }

然后在这里调用这个方法:

ClickableRectangle recto(1,1,100,100);
recto.drawClickableRectangle(recto);

这是完整的类(class):

class ClickableRectangle
{
    // Access specifier
public:


    // Data Members
    int xpos, ypos, width, height;
    ClickableRectangle(int x1, int y1, int width1, int height1){
        xpos = x1;
        ypos = y1;
        width = width1;
        height = height1;
    };
    // Member Functions()
    int getxpos()
    {
        return xpos;
    }
    int getypos(){
        return ypos;
    }
    int getwidth(){
        return width;
    }
    void drawClickableRectangle(ClickableRectangle recto){
        ofSetHexColor(0xffffff);
        ofFill();
        ofRect(recto.xpos,recto.ypos, recto.width, recto.height);
        //ofDrawRectangle(recto.xpos, recto.ypos, recto.width, recto.height);
    }

有没有办法让函数调用“自反”?所以我可以这样调用它:

recto.drawClickableRectange();

我是 C++ 的新手,但对一般编程不是很熟悉。谢谢!

最佳答案

你可以在 C++ 中这样做:

class ClickableRectangle {

    public int xpos;
    public int ypos;
    public int width;
    public int height;

    void drawClickableRectangle(){
        ofSetHexColor(0xffffff);             // just some syntax from the library I'm using
        ofFill();
        ofDrawRectangle(xpos, ypos, width, height);
    }
}

然后在你的主函数中,这样调用它:

int main(){

    ClickableRectangle recto;
    recto.xpos = 1;
    recto.ypos = 1;
    recto.width = 100;
    recto.height = 100;
    recto.drawClickableRectange();
    return 0;
}

关于对象本身作为参数的对象上的 C++ 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350949/

相关文章:

由值返回的 C++ 类实例不像右值

c++ - 为什么这个 fwrite 写的是垃圾?

c# - C#中的重用抽象原则

java - 寻找一个奇完全数

java - 如何对二维数组进行列和和行和方法?

c++ - 如何在Dev C++ IDE中启用C++ 11或C++ 14

c++ - OpenCV:矩阵元素访问

perl - 如何将模块的函数作为对 Perl 中另一个模块的引用传递?

c++ - 我应该怎么做才能让 WS_MAXIMIZE 工作?

java - 在java中为抽象类创建方法