我有一个Flight
类,我需要实现两个操作:
Flight s;
auto value = s(1, 2);
s(3, 4) = value;
我知道如何执行首次操作:class Flight
{
public:
int operator()(int a, int b) {
return cache.for(a, b).get();
}
private:
// cache
}
但是我不知道执行第二次操作。像这样:void operator()=(int a, int b, int value) {
cache.for(a, b).set(value);
}
现在我有一个类似于operation is not accessible for
的s(3, 4) = value;
表达式错误。如何执行此操作?
最佳答案
没有()=
运算符。它是两个单独的运算符-operator()
,然后是operator=
的返回值。
由于要在缓存中使用单独的operator()
和get()
方法,因此必须使set()
返回帮助代理,然后可以实现Flight::operator()
调用proxy::operator int
方法和get()
调用proxy::operator=
方法,例如:
class Flight
{
public:
class Proxy
{
private:
Flight &f;
int a, b;
public:
Proxy(Flight &f, int a, int b) : f(f), a(a), b(b) {}
operator int() {
return f.cache.For(a, b).get();
};
Proxy& operator=(int value) {
f.cache.For(a, b).set(value);
return *this;
}
};
friend class Proxy;
Proxy operator()(int a, int b) {
return Proxy{*this, a, b};
}
private:
// cache
};
然后,您的示例将按需要工作:Flight s;
int value = s(1, 2); // <-- important - int, not auto!
s(3, 4) = value;
Live Demo
关于c++ - 如何实现 `my_class_instance(a, b) = value`操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63944410/