The const object of C + + can only invoke the Const member function---Supplement (18) "more effective C + +" __jquery

Source: Internet
Author: User

In C + +, the Const object can only invoke the const member function, for what reason. Let's look at the following examples and analyze them to understand why:

#include <iostream>
#include <string>
using namespace std;
Class myint{
private:
    int i;
Public:
    MyInt () {

    }
    MyInt (int i): I (i) {

    }
    myint& operator++ () {
        this->i = 1;
        return *this;
    }
    Const MYINT operator++ (int) {
        MyInt oldint = MyInt (*this);
        This->i + 1;
        return oldint;
    }
    void Show () {
        cout << i << endl;
    }
};

int main () {
    MyInt mi (mi2);
    Mi2++.show ();
    return 0;
}

Compile an error:

We can see that the compiler complains that the Const Myint cannot be converted to Myint&, and that there are some conversion problems when the Const object calls the non-const member function, so let's take a look at the following analysis: The const object cannot invoke a non-const member function:
Void Show () is equivalent to void show (myint* this), not a const object that mi2 call is mi2.show (), That is, a non-const object is passed the pointer that myint* this entry, so the show function executes successfully.
What about the const object? const MYINT MI3 (10), now equivalent to the type of argument currently passed in is a const myint*, at which point passing the pointer to the myint* has a conversion failure problem. Therefore, a const member object cannot invoke a non-Const member object. The const object can call the const member function: The
Const object can invoke the const member function because the const member function default argument is const myint* This, we create a const object, that is, the pointer passed in is still a const myint*, so the call succeeds.

Related Article

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.