zoukankan      html  css  js  c++  java
  • C++函数传递类对象和类对象的引用

     1 #include <iostream>
     2 #include<string>
     3 using namespace std;
     4 
     5 class Point {
     6 public:
     7     Point(int a, int b) :x(a), y(b) {};
     8     //Point(Point& p) :x(p.x), y(p.y) {};
     9     int getX() { return x; }
    10     int getY() { return y; }
    11     void print() {
    12         cout << "x: " << x << endl << "y: " << y << endl;
    13     }
    14 private:
    15     int x, y;
    16 };
    17 
    18 Point re_Ponit(int a,int b) { 
    19     Point res(a, b); //创建的是局部变量
    20     return res;  //传递对象实体
    21 }
    22 
    23 Point& re_PonitReference1(int a, int b) {
    24     Point res(a, b); //创建的是局部变量
    25     return res;  //传递对象引用(类似指针)
    26 }
    27 
    28 Point& re_PonitReference2(int a, int b) {
    29     Point* res = new Point(a, b); //动态内存分配
    30     return *res;  //传递对象引用
    31 }
    32 
    33 
    34 int main()
    35 {
    36     Point a1 = re_Ponit(1, 2); //复制构造
    37     Point& a2 = re_PonitReference1(2, 3); //引用赋值(该函数传递的是一个局部变量的引用)
    38     Point& a3 = re_PonitReference2(2, 3); //引用赋值(该函数传递的是一个堆内存变量的引用)
    39     a1.print(); //1,2
    40     a2.print(); //随机值
    41     a3.print(); //2,3
    42 }

  • 相关阅读:
    使用基本的socket函数
    ODBC、ADO
    MFC开发ActiveX控件的简介
    MFC线程
    系统API函数实现多线程及线程同步
    IP地址控件
    加速键
    属性页对话框
    Tab控件
    树控件
  • 原文地址:https://www.cnblogs.com/NiBosS/p/12152802.html
Copyright © 2011-2022 走看看