例如,在 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/