在网上某处查看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。
那么,有人可以向我解释一下这里到底发生了什么吗?
最佳答案
你的声明
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);
}
关于Structure 内部的 C++ Class 和两个同时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48976358/