您的位置:首页 > 其它

拷贝函数访问本类的私有变量的问题

2010-04-14 09:48 218 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: