C/c++:c++ references

Source: Internet
Author: User


C + + references:

First, write a program like this:


#include <iostream>class point{private:    int x, y;public: Point    (int x, int y) {        this->x = x;        This->y = y;    };    int GetX () {        return x;    }    int GetY () {        return y;    }    void Add (point p) {        this->x + = p.x;        This->y + = P.y;    }}; int main () {point    P (1, 1);    P.add (Point (2, 2));    Std::cout << p.getx () << Std::endl;    Std::cout << p.gety () << Std::endl;    return 0;}


Well, let's analyze this procedure, and when we execute the P.add method, we define an object of such a point,

To pass the value to it. And in the Add method we have defined a variable. and passing a value to another variable is the default execution

The process of a memory copy, and that certainly takes time. Of course, the words here are not going to take much time, if your program

Very large, you write like this, it is another matter, and this type of copy is completely unnecessary. and C + + gives us a

Reference (&) This function, of course, we can also use pointers to do ... Using a quote, we just have to change it a little bit.


#include <iostream>class point{private:    int x, y;public: Point    (int x, int y) {        this->x = x;        This->y = y;    };    int GetX () {        return x;    }    int GetY () {        return y;    }    void Add (Point &p) {        this->x + = p.x;        This->y + = P.y;    }}; int main () {point    P (1, 1);    Point A (2, 2);    P.add (a);    P.add (Point (2, 2));    Std::cout << p.getx () << Std::endl;    Std::cout << p.gety () << Std::endl;    return 0;}

This way we also avoid the process of the memory copy.



PS: Come on!



C/c++:c++ references

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.