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

C++ call method on object with the object itself as parameter

本文关键字:对象 调用 方法 参数 C++      更新时间:2023-10-16

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

与python不同,不。

在python中,你可以

def unattached(fake_self):
return fake_self.x
class Thing:
def __init__(self):
self.x = 42
Thing.method = unattached
thing = Thing()
print (thing.method())
print (unattached(thing))

因为具有显式第一个参数的自由函数和具有隐式第一个参数的实例方法之间没有区别。

在 C++ 中,不能在运行时更改class,并且成员函数的类型与自由函数的类型不同。

struct Thing {
int x = 42;
int method() const { return this->x; }
}
int unattached(const Thing * thing) { return thing->x; }

unattached的类型是int (*)(const Thing *),而methodint (const Thing::*)()。这些是不同的类型,您无法将一种切换为另一种。但是,您可以从它们中的任何一个构造一个std::function<int(const Thing *)>,但您只能将其与自由函数语法一起使用func(thing),因为它不是Thing的成员