【问题标题】:C++ Class inside Structure and two callings at the same time结构内部的C ++类和同时两个调用
【发布时间】:2018-02-25 17:27:54
【问题描述】:

在网上某处查看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 中的返回类型,则会出现错误。此外,如果 t1.addOptions()(5,5); 将更改为 res = t1.addOptions()(5,5); 其中 res 被声明为 mypair 那么我也会得到一个错误。 void operator()(int x1, int y1)addOption 之后调用,但最后 g.x 和 g.y 的值都是 3 而不是 5。

那么,谁能解释一下这里到底发生了什么?

【问题讨论】:

    标签: c++ class struct parameter-passing variadic-functions


    【解决方案1】:

    你的陈述

    t1.addOptions()(5,5);
    

    基本上是这样工作的:

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

    注意,由于myrot::addOptions 返回mypair 对象按值mypair::operator() 函数在myrot::g 成员变量的副本 上调用。如果你想修改myrot::g 变量你必须返回引用

    mypair& addOptions() { ... }
    

    那么等价的代码就变成了

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

    【讨论】:

    • 嘿,谢谢!这是澄清一点上面的代码。那么使用这种复杂而神秘的代码有什么好处呢?这个有名字吗?
    • @LightnessRacesinOrbit 我不确定我是否理解你的答案......你只是说这种技术没有技术名称,这是一种聪明的方式来完成这项工作吗?我真的不明白你想说“而且它不会通过我团队的代码审查”
    【解决方案2】:

    如果我删除成员函数 addOptions 中的返回类型,则会出现错误。

    如果您将 addOptions 返回类型更改为 void,则不会返回任何内容,并且您将收到错误消息,因为不会调用 operator()。

    如果 t1.addOptions()(5,5);将改为 res = t1.addOptions()(5,5); res 被声明为 mypair 然后我也得到一个错误。

    这是另一种方式。您声明 () 运算符返回 void。所以 res 中没有什么可以保存的。

    这只是方法的串联。

    顺便说一句,你的类名应该以大写字母开头。并且您在 addOption 中的参数应该声明为 x 和 y 以及您的类成员 _x 和 _y 或者我更喜欢的:

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

    【讨论】:

    • 感谢 Maik,这两个例子(你的和“一些程序员老兄”)现在我都清楚了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多