zoukankan      html  css  js  c++  java
  • 对象与私有成员变量恩仇录

    1.对象引用与对象指针:

    https://www.cnblogs.com/Free-Thinker/p/4950303.html

    2.对象作为函数参数与对象引用作为函数参数:

    对象作为函数参数,是复制传递,会调用拷贝构造函数,通过对象参数,不可以改变对象成员变量的值

    对象引用作为参数,是引用传递,传递的是对象的地址,通过对象引用,改变对象成员变量的值

    3.在类成员函数中函数的参数为该类的对象或对象的引用、函数的临时变量为该类的对象,该对象或对象的引用可以访问它们的私有成员变量

    4.在类的外部,对象不可以访问对象的私有成员变量

     1 #include"iostream"
     2 using namespace std;
     3 class A
     4 {
     5 int y;
     6 public:
     7     A(int y)
     8     {
     9         this->y = y;
    10     }
    11 };
    12 
    13 class test
    14 {
    15 int x;
    16 
    17 public:
    18     
    19     test(int x)
    20     {
    21         this->x = x;
    22     }
    23     
    24     test(test &t)
    25     {
    26         x = t.x;
    27         cout<<"拷贝构造函数被调用"<<endl;
    28     }
    29     
    30     void fun(test &t1)
    31     {        
    32         test ttt(9);
    33         cout<<ttt.x<<endl;//在类的成员函数中,允许直接访问该类的成员对象的私有成员变量
    34         t1.x = 400;
    35         cout<<t1.x<<endl;//本类对象的引用作为参数,可以直接访问其私有成员
    36     }
    37     void fun1(test t1)
    38     {        
    39         t1.x = 500;
    40         cout<<t1.x<<endl;
    41         //A a(55);
    42         //cout<<a.y<<endl; //在A类的类外,其对象不可以访问其私有成员变量
    43     }
    44 };
    45 
    46 int main()
    47 {
    48     test t11(5),t22(6);
    49     //cout<<t11.x<<endl; //对象在类外不可以访问私有成员变量
    50     t11.fun(t22);
    51     t11.fun1(t22);
    52     t11.fun(t22);
    53     return 0;
    54 }
  • 相关阅读:
    MFC Windows 程序设计>WinMain 简单Windows程序 命令行编译
    AT3949 [AGC022D] Shopping 题解
    CF643D Bearish Fanpages 题解
    CF643C Levels and Regions 题解
    CF241E Flights 题解
    CF671C Ultimate Weirdness of an Array 题解
    CF1592F Alice and Recoloring 题解
    GYM 102452E 题解
    CF494C Helping People 题解
    P5556 圣剑护符
  • 原文地址:https://www.cnblogs.com/GoldenEllipsis/p/10771942.html
Copyright © 2011-2022 走看看