c++随手记——嵌套类

类中定义一个类的用法就称之为嵌套类。类之间的相互访问用友元函数来声明。

作用……没有体会到有什么用。

值得注意的是:

1.嵌套类也分public和private,外界的访问需要注意是public和private,否则不能随意访问。

2.嵌套类之后,size还是1.

实例代码如下:

#include<iostream>
using namespace std;

class A{
    public:
    int a;
        class B{int b;};
};


class RGWDataAccess
{
  int m_s32RgwData;
public:
  RGWDataAccess(int s32RgwData):m_s32RgwData(s32RgwData){}
  int getRGWDataAccess(){
    return m_s32RgwData;
  }
  class Object;
  class Bucket;

  friend class Bucket;
  friend class Object;
  class Bucket
  {
    //friend class RGWDataAccess;
    //friend class Object;
    int m_s32BucketData;
  public:
    
    Bucket(int s32BucketData):m_s32BucketData(s32BucketData){}
    int getBucketData(){return m_s32BucketData;}

  };


  class Object 
  {
    friend class RGWDataAccess;
    //friend class Bucket;
    int m_s32ObjectData;
    
  public:
    Object(int s32ObjectData):m_s32ObjectData(s32ObjectData){}
    int getObjectData(){
      return m_s32ObjectData;
    }
  };

};

int main()
{
    RGWDataAccess rgwData(5);
    RGWDataAccess::Bucket bucket(10);
    RGWDataAccess::Object object(15);

    cout<<"rgwData.data:"<<rgwData.getRGWDataAccess()<<endl;
    cout<<"object.data:"<<object.getObjectData()<<endl;
    cout<<"sizeof(A):"<<sizeof(A)<<endl;
    cout<<"sizeof(B):"<<sizeof(A::B)<<endl;


    system("pause");
    return 0;
}

 

 

参考博客:

https://cloud.tencent.com/developer/article/1177286

 

posted on 2019-07-12 11:06  陶大先生  阅读(204)  评论(0编辑  收藏  举报

导航