一 this指针
this是隐藏的指针,在创建对象时赋值,它指向正在被该成员函数操作的那个对象,类型与对象的指针类型一致。this是关键字,只能在类内函数中使用,类外无效
#include<iostream>
using namespace std;
class AA
{
private:
int a;
public:
AA(int n)
{
this->a=n;
}
void show(/* AA * this */)
{
cout<<this->a<<endl;
}
};
class BB
{
private:
int a;
public:
AA(int a)
{
this->a=a;
}
};
int main()
{
AA a1(100);
a1.show();
system("pause");
return 0;
}
二 拷贝构造函数
拷贝构造函数在类中是隐藏的,本身就有默认拷贝构造函数,拷贝构造函数的调用条件是:
(1)用一个对象去初始化另一个对象。
(2)类对象作为函数参数时。
(3)类对象作为参数时。
#include<iostream>
using namespace std;
class AA
{
public:
int a;
public:
AA()
{
}
AA(AA &a)
{
this->a=a.a;
cout<<"AA COPY"<<endl;
}
};
void Func(AA a)
{
cout<<a.a<<endl;
}
AA Fun()
{
AA a;
a.a=100;
return a;
}
int main()
{
AA a1;
a1.a=100;
AA a2=a1;//拷贝构造函数
AA a3(a1);//拷贝构造函数
Func(a1);//调用拷贝构造函数
cout<<Fun().a<<endl;//调用拷贝构造函数
system("pause");
return 0;
}
三 浅拷贝和深拷贝
浅拷贝是将源对象的值拷贝到目标对象 ,如果有delete就会崩,解决方法就是引用&或者改成深拷贝。
浅拷贝
#include<iostream>
using namespace std;
class AA
{
public:
int *p;
public:
AA()
{
p=new int (100);
}
~AA()
{
delete p;
}
};
int main()
{
AA a1;
cout<<*a1.p<<endl;
AA a2=a1;
cout<<*a2.p<<endl;
system("pause");
return 0;
}
修改为引用
#include<iostream>
using namespace std;
class AA
{
public:
int *p;
public:
AA()
{
p=new int (100);
}
~AA()
{
delete p;
}
};
void Fun(AA &a)
{
cout<<*a.p<<endl;
}
int main()
{
AA a1;
Fun(a1);
system("pause");
return 0;
}
深拷贝 拷贝时先开辟一个跟源对象空间大小一样的空间,然后再将空间的内容复制过来
#include<iostream>
using namespace std;
class AA
{
public:
int *p;
public:
AA()
{
p=new int (100);
}
AA(AA &a)
{
p=new int;
*p=*a.p;
}
~AA()
{
delete p;
}
};
void Fun(AA a)
{
cout<<*a.p<<endl;
}
int main()
{
AA a1;
Fun(a1);
system("pause");
return 0;
}
stactic
静态变量只在当前的.cpp里面好使,静态变量只有一份,所有对象共享,在类外初始化
#include<iostream>
using namespace std;
class AA
{
public:
static int a;
};
int AA::a=100;
int main()
{
AA a1;
cout<<a1.a<<endl;
a1.a=300;
AA a2;
cout<<a2.a<<endl;
system("pause");
return 0;
}