14.4 value assignment operator
Class1 & operator = (int I)
{
Counter = I;
Return * this;
}
The value assignment operator can be overloaded. Regardless of the type of the parameter, the value assignment operator must be defined as a member function, which is different from the compound value assignment operator.
Copy must return a reference to * this.
Generally, the copy operator and the compound value assignment operator should return a reference to the left operand.
14.5 subscript operator
Subscript operators must be defined as class member functions.
1. read/write access
Defining subscript operators is complicated because they should be normal when used as the left and right operands of values. The subscript operator appears on the left and must generate the left value. You can specify the reference as the return type to get the right value. As long as the subscript operator returns a reference, it can be used as any party of the value assignment.
It is also a good idea to use subscript for const and non-const objects. When applied to a const object, the return value should be referenced by the const object, so it cannot be used as the target of the value assignment.
When defining subscript operators for a class, two versions are generally required: one is a non-const member and the other is a const member, and the other returns a const reference.
2. Prototype subscript operator
Class Foo
{
Public:
Foo (int len)
{
Vec = vector <int> (len );
}
Int & operator [] (const size_t index)
{
Return vec [index];
}
Const int & operator [] (const size_t index) const
{
Return vec [index];
}
Private:
Vector <int> vec;
};
From xufei96's column