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

#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



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

猜你喜欢

转载自blog.csdn.net/ylcangel/article/details/18188615
今日推荐