![](/img/trans.png)
[英]C++ Operator “=” overload - Get all values in vector on lhs to equal a double value on rhs
[英]C++ Can I overload the bracket [] operator to do different things if it on the LHS vs RHS of an assignment?
我希望完成以下任務:
int x, y, z;
foo[x] = y;
行為類似於do_this(x,y);
z = foo[x];
像z = do_that(x)
I can accomplish the first with a Foo
class and a Helper
class, where the operator[]
returns by value a Helper
class constructed with x
, and the operator=
for the Helper
class is defined to run do_this(this->x, y)
. 如下所示:
class Foo {
public:
Helper operator[](int x) {
return Helper(x);
}
};
class Helper {
public:
Helper(x) {
this->x = x;
}
void operator=(int y) {
do_this(this->x, y);
}
private:
int x;
};
我不知道如何完成(2)。 有沒有辦法重載operator[]
以便它知道它是用於 lhs 還是 rhs?
是的 - 給你的Helper
class 一個轉換 function 到int
:
class Helper {
public:
Helper(x){
this->x = x;
}
Helper& operator= (int y) {
do_this(this->x, y);
return *this;
}
operator int() const {
return do_that(this->x);
}
private:
int x;
};
這也將允許其他用途,例如product *= foo[x];
或func_taking_int(foo[x])
等。
一個潛在的問題是auto
或 function 模板的某些使用仍將保留類型Helper
,這可能不是我們想要的 - 所以Foo
的用戶仍然應該了解這個代理糖正在發生。 對於此類情況,在Foo
或Helper
中使用一些替代語法來顯式獲取int
值也可能會有所幫助。
我不確定我是否理解您真正想要做的事情,但您可能能夠使用operator[]
的const
版本與非const
版本。 例如:
struct Foo {
Z operator [] (int x) const { // this last const is important
return do_that(x);
}
Helper operator [] (int x) {
// as you yourself have written.
}
};
還有更多提示和技巧,用於完美地轉發 arguments(又名“完美轉發”),以實現“const 正確”,以及許多其他小事,但其要點如上所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.