C ++ вызов метода для объекта с самим объектом в качестве параметра - PullRequest
0 голосов
/ 15 мая 2018

В 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);
    }

IsЕсть ли способ сделать вызов функции "рефлексивным"?Поэтому я могу назвать это просто:

recto.drawClickableRectange();

Я относительно новичок в C ++, но не в программировании в целом.Спасибо!

Ответы [ 2 ]

0 голосов
/ 15 мая 2018

Не так, как 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

0 голосов
/ 15 мая 2018

Вы можете сделать это в 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;
}
...