zoukankan      html  css  js  c++  java
  • C++ 的一个问题的理解(私有变量成员)

    class CExample
    {
    public:
        CExample(){pBuffer=NULL; nSize=0;}
        ~CExample(){delete pBuffer;}
        CExample(const CExample&); 
    void Init(int n){ pBuffer=new char[n]; nSize=n;}
    private:
        char *pBuffer; 
        int nSize;
    };
    CExample::CExample(const CExample& RightSides) 
    {
        nSize=RightSides.nSize; //!!!!!!请注意这句话!!!!!!
        pBuffer=new char[nSize];
        memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char));
    }

    感叹号部分我很奇怪,不是不允许对象许访问私有变量成员么?怎么回事,而且还能编译通过。

    1.为什么对象a可以直接访问私有的x(a.x)成员见http://topic.csdn.net/u/20110504/22/738aede9-3909-4d74-82fd-8d4a2f2f12a5.html

    给出了一个解答:因为A(const A&a)是他的成员函数。

    在我的例子也是如此:CExample::CExample(const CExample& RightSides)是CExample的成员函数,所以可以访问同类型对象的私有成员。即RighSides.nSize的调用可以编译用过,但是,你在main函数里面直接写上:

    int main(int argc, char* argv[])
    {
    CExample theObjone;
    theObjone.nSize;
    return 0;
    }

    编译器肯定是报错,提示你nSize是私有变量,不允许对象进行访问。
    随后,我又做了一个实验:

    #include <iostream>
    
    using namespace std;
    class T{
    private:
        int m_data;
    };
    class CTest
    {
    public:
     CTest();  //构造函数
     CTest(const CTest &); //复制构造函数
     CTest & operator = (const CTest &); //赋值符
     void print(){
         cout << m_data << endl;
     };
    int print1(const CTest &);
    int print2(const T&);
    private:
     int m_data;
    };
    
    CTest::CTest()
    {
     cout<<"Constructor of CTest"<<endl;
    }
    
    CTest::CTest(const CTest& arg)
    {
        cout << arg.m_data <<endl;
        cout<<"Copy Constructor of CTest"<<endl;
    }
    
    CTest & CTest::operator = (const CTest & arg)
    {
     cout<<"Assign function of CTest"<<endl;
    }
    int CTest :: print1(const CTest & arg){
        cout << arg.m_data <<endl;
        return 0;
    }
    int CTest::print2(const T& arg){
        cout << arg.m_data << endl;
    }
    int main()
    {
     CTest a;
     return 0;
    }

    请注意print()、print1()、print2()的区别;

    print()自然不用说,成员函数访问类的私有变量,编译通过;

    print1():print1是CTest类的成员函数,而print1的形参是const CTest& arg,arg的类型就是CTest,根据成员函数可以访问私有变量,故编译通过

    print2():print2是CTest类的成员函数,但是print2的形参类型是T,不是CTest,print2不是T的成员函数,不能访问类的私有变量,故编译不能通过

    转自:http://blog.csdn.net/randyjiawenjie/article/details/6667146

  • 相关阅读:
    程序员你写的代码,被爆出黑产了!
    .NET面试题系列之面向对象
    .NET必问的面试题系列之基本概念和语法
    xamarin开发android收集的一些工具
    C#爬虫使用代理刷csdn文章浏览量
    我们必须要知道的RESTful服务最佳实践
    MVP架构在xamarin android中的简单使用
    使用Xamarin实现跨平台移动应用开发(转载)
    博客园app for xamarin android一款简洁阅读的博客园android客户端
    vs2019企业版密钥
  • 原文地址:https://www.cnblogs.com/liushui-sky/p/5920065.html
Copyright © 2011-2022 走看看