如何让C++类成员函数实现无需传入自身对象的自引用调用?
让C++类成员函数实现自引用调用的方法
嘿,刚接触C++的话,这个问题刚好能帮你理解类成员函数里隐含的this指针——这正是实现你想要的“自引用”调用的关键!
问题根源
你现在的drawClickableRectangle函数要求传入一个ClickableRectangle对象,但其实当你在类的成员函数里时,C++会自动给你一个指向当前调用对象的指针this,完全没必要再把自己传进去。
修改步骤
我们只需要做两处小修改:
- 修改成员函数的签名:去掉函数参数里的
ClickableRectangle recto - 修改函数内部的成员访问方式:把所有
recto.xpos这类写法,换成直接访问成员(或者显式用this->xpos,效果一样)
修改后的完整代码
类定义
class ClickableRectangle { // Access specifier public: // Data Members int xpos, ypos, width, height; // Constructor 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(){ ofSetHexColor(0xffffff); ofFill(); // 直接用成员变量,编译器会自动通过this指针访问 ofDrawRectangle(xpos, ypos, width, height); // 也可以显式写this->xpos,效果完全一样,适合新手理解 // ofDrawRectangle(this->xpos, this->ypos, this->width, this->height); } };
调用代码
// 创建对象 ClickableRectangle recto(1,1,100,100); // 直接调用,无需传参 recto.drawClickableRectangle();
额外优化建议
如果这个绘图函数不会修改类的成员变量,建议给函数加上const修饰,这样它就能被const对象调用,代码也更规范:
void drawClickableRectangle() const { ofSetHexColor(0xffffff); ofFill(); ofDrawRectangle(xpos, ypos, width, height); }
这样就完美实现了你想要的简洁调用方式啦!
内容的提问来源于stack exchange,提问作者CatzRevenge
相关产品推荐
相关产品推荐

