C++对象本身作为参数调用对象的方法
C++ call method on object with the object itself as parameter
例如,在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 *)
,而method
是int (const Thing::*)()
。这些是不同的类型,您无法将一种切换为另一种。但是,您可以从它们中的任何一个构造一个std::function<int(const Thing *)>
,但您只能将其与自由函数语法一起使用func(thing)
,因为它不是Thing
的成员
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 检查哪个对象调用了另一个对象的对象方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 从 Base 引用对象调用派生类的成员
- 为什么为未删除的对象调用析构函数?
- Qt c++不会为所有对象调用move_slot.为什么?
- 使用在堆栈上创建的对象调用虚拟函数
- 使用基类对象调用Dervied Class函数
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 从类中的对象调用类中的函数的最佳方法
- 派生对象调用的 Base 方法的模板推导
- 如何使用单个对象调用具有相同名称的两个类函数
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 如果类没有任何成员变量,则通过临时对象调用类的成员函数的开销是多少?
- 如何对动态数组中的某些对象调用析构函数
- 如何从列表中存储的对象调用成员函数
- 从线程内的对象调用静态方法
- 从成员对象调用方法
- 当包含它的对象调用其析构函数时,unique_ptr是否未分配
- 从对象调用成员对象,错误:引用非常量值的初始值必须是左值