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

本文介绍了C++中类的实现细节,包括构造函数、拷贝构造函数及成员函数的使用。重点展示了如何进行深度拷贝,并解释了在类内部如何访问私有成员变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值