Chapter 4 heavy-duty operators and transformations (4)

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.