复制构造函数,赋值操作符、关系操作符,const函数

本文详细介绍了C++中类的实现方式,包括构造函数、析构函数、复制构造函数及赋值操作符的使用,并展示了如何管理类内部的指针资源。此外,还讨论了const成员函数的应用场景及类间引用时的注意事项。

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

#include <iostream>
using namespace std;

class A {
private:
int *val;
public:
A(int v) {
cout << "into constructor" << endl;
val = new (int);
*val = v;
}
~A() {
if (val != NULL) {
cout<<"delete pointor val"<<endl;
delete val;
}
}


/**

* 复制构造函数 此处注意  const,用于初始化对象复制而来

*/
A(const A& a){
cout<<"into copy constructor"<<endl;
val = new(int);
*val = *(a.val);
}
/**
* 赋值函数,赋值操作符,同样const ,用于赋值,这个被赋值的对象已经被初始化过
*/
A& operator=(const A& a){
cout<<"into operator ="<<endl;
if(&a != this){
delete val;
val = new(int);
*val = *(a.val);
}
return *this;
}
void setVal(int v) {
if (val != NULL) {
*val = v;
}
}


/**
* const 函数对于外部const 对该对象的引用,可以看到B类里面传入参数为const型,如果这里不加const,B类的那个方法不会编译过通过,代表函数不用修改对象
*/
int getVal() const{
if (val != NULL) {
return *val;
}
return 0;
}


/**
* 关系操作符,类似java中的equals方法
*/
bool operator==(const A& a){
if(*(a.val) == *(val)){
return true;
}
return false;
}
};


class B{
public:
void show(const A& a){//上面方法必须加const
cout<<a.getVal()<<endl;
}


};
int main() {
A a(10);
cout<<a.getVal()<<endl;
A b = a;
b.setVal(13);
cout<<b.getVal()<<endl;
cout<<a.getVal()<<endl;
if(a == b){
cout<<"yes"<<endl;
}


cout<<"===================="<<endl;
a = b;
cout<<a.getVal()<<endl;
if(a == b){
cout<<"true"<<endl;
}


B ba;
ba.show(a);


return 0;

}


运行结果:

=========================================================================

into constructor
10
into copy constructor
13
10
====================
into operator =
13
true
13
delete pointor val
delete pointor val



这篇文章作为我的笔记,自己忘记时就过来看看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值