C++ Class inside Structure 和两个同时调用

C++ Class inside Structure and two callings at the same time

在网上找了一段c++代码,发现有这样一段代码

 opts.addOptions()(cOSS.str(), m_list, XYentry());

这段代码的实现方式给我留下了深刻的印象,当然我想知道它是如何工作的。

所以我尝试复制这种类型的调用:

#include "stdafx.h"
#include "iostream"


using namespace std;

class mypair {
public:

    int x;
    int y;

    mypair() {

        x = 0;
        y = 0;
    }

    void operator()(int x1, int y1) {
        x = x1; 
        y = y1;
        cout << "x=" << x << "  y=" << y << endl;
    }

};



struct myrot {
    int     left;
    int     right;
    int     result;
    mypair  g;

    mypair  addOptions() {

        g.x = 3;
        g.y = 3;
        cout << "g.x=" << g.x << endl;
        cout << "g.y=" << g.y << endl;
        return g; 
    };

    void print_mypair() {

        cout << "g.x=" << g.x << endl;
        cout << "g.y=" << g.y << endl;

    }

    void operator()(int y) { result = y; }
    void operator() (void) {
        cout << "g.x=" << g.x << endl;
        cout << "g.y=" << g.y << endl;

    }


};

int main()
{


    myrot    t1;
    mypair  res;

    t1.left = 2;
    t1.right = 5;

    t1.addOptions()(5,5);
    t1.print_mypair();
    cout << "t1.g.x=" << t1.g.x << endl;

    return 0;
}

调用 t1.addOptions()(5,5); 至少在语法级别上看起来几乎相同。所以我的问题是:

1) 这种叫法有名字吗? 2)它是如何工作的?如果我删除成员函数 addOptions 中的 return 类型,则会出现错误。此外,如果 t1.addOptions()(5,5); 将更改为 res = t1.addOptions()(5,5);,其中 res 被声明为 mypair,那么我也会得到一个错误。 void operator()(int x1, int y1)addOption 之后调用,但最后 g.x 和 g.y 都具有值 3 而不是值 5。

那么,有人可以向我解释这里到底发生了什么吗?

你的说法

t1.addOptions()(5,5);

基本上是这样工作的:

{
    mypair temp_variable = t1.add_options();
    temp_variable(5, 5);
}

请注意,由于 myrot::addOptions return 是 mypair 对象 的值 ,因此 mypair::operator() 函数在复制 myrot::g 成员变量。如果你想修改 myrot::g 变量你必须 return by reference:

mypair& addOptions() { ... }

那么等价的代码就变成了

{
    mypair& temp_variable = t1.add_options();
    temp_variable(5, 5);
}

If I remove the return type in the member function addOptions then I get error.

如果您将 addOptions return 类型更改为 void,则不会 return 编辑任何内容,您将收到错误消息,因为没有任何内容可调用 operator() 。

Also if t1.addOptions()(5,5); will be changed to res = t1.addOptions()(5,5); where res is declared as mypair then I get also an error.

这是另外一种方式。您将 ()-运算符声明为 return 无效。所以res没有什么可保存的

这只是方法的串联。

顺便说一下,您的 class 名字应该以大写字母开头。您在 addOption 中的参数应声明为 x 和 y,而您的 class 成员要么是 _x 和 _y,要么是我喜欢的:

void operator()(int x, int y) {
    this->x = x; 
    this->y = y;
    cout << "x=" << x << "  y=" << y << endl;
}