c++学习笔记 三

一 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值