拷貝函數訪問本類的私有變量的問題

chap_5.h

——————————————————————————————————————————————————————————

#ifndef CHAP_5_H
#define CHAP_5_H
#include "string"
#include "iostream"
using namespace std;
class B
{
public:
 B(int a,int b);
private:
 int b1,b2;
};
B::B(int a,int b):b1(a),b2(b){}


class A
{
public:
 A(int a,int b);
 A(const A&);
 void Test(const B &);
 void Test(const A &);
private:
 int x,y;
 char *pbuffer;
};
A::A(int a,int b)
{
 x=a;
 y=b;
 pbuffer=new char[10];
 strcpy(pbuffer,"012345678");
}
A::A(const A & t)//這屬於深度拷貝,因爲將t所擁有的資源拷貝了一份給this對象
{

 x=t.x;
 y=t.y;
 pbuffer=new char[10];
 memcpy(this->pbuffer,t.pbuffer,10);//我們看到此時用的t.pbuffer是可以訪問的,這主要原因在於private是針對類的不是限制對象的,如果在類內的成員函數不能知道類的結構那麼定義類也就沒有什麼意義,但是如果在類外使用a2.pbuffer這就是不允許的
 //但是如果是其他類的成員如B,這樣就是不可以的,因爲Private限定了不同類之間的關係
 cout<<"調用拷貝構造函數/n"<<pbuffer<<endl;
}
void A::Test(const B &b)
{
 //cout<<"test!!!!!!!!"<<b.b1<<endl;//是不可以訪問的,可以讓B類提供接口
}
void A::Test(const A &a)
{
 cout<<"test!!!!!!!!"<<a.pbuffer<<endl;//我們可以看出,作爲類的成員函數是可以訪問同類型的私有變量的。
}
#endif

___________________________________________________________________________________________

// chap_5.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "chap_5.h"

int _tmain(int argc, _TCHAR* argv[])
{
 A a1(1,2);
 A a2=a1;
 B b1(1,2);
 a2.Test(b1);
 a2.Test(a1);
 int i;
 cin>>i;
 return 0;

 

發佈了16 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章