C++笔记(七)类与对象

一、实例化对象的两种方法

#include<iostream>
#include<string>
using namespace std;

class human{
private:
	int age;
	string name;
	string sex;
	string DateOfBirth;
public :
	void SetName(string a){
		name=a;
	}
	void SetAge(int  a){
		age=a;
	}
	void introduce(){
		cout<<"my mane is "+name<<" and i'm "<<age<<" years old"<<endl;
	}
};
int main(){
	human p1;
	p1.SetAge(10);
	p1.SetName("aaa");
	p1.introduce();


	human*p2=new human();
	p2->SetAge(20);
	p2->SetName("bbb");
	p2->introduce();
	delete p2;

	return 0;
}
输出:
my mane is aaa and i'm 10 years old
my mane is bbb and i'm 20 years old
请按任意键继续. . .

二、构造函数

创建对象时被调用的函数,可以被重载。

2.1. 申明与实现

与类同名,无返回值

类内申明与实现

class human{
private:
	int age;
	string name;
public :
	human(int a,string b){
		name=b;
		age=a;
	}
};

类内申明,类外实现,使用::作用域解析运算符。

class human{
private:
	int age;
	string name;
public :
	human(int a,string b);
};
human::human(int a,string b){
	name=b;
	age=a;
}

2.2. 使用

构造函数在创建对象时被调用

2.3. 重载

class human{
private:
	int age;
	string name;
public :
	human(){
		age=0;
		name="";
	}
	human(int a){
		age=a;name="";
	}
	human(string b){
		age=0;
		name=b;
	}
	human(int a,string b){
		age=a;
		name=b;
	}
};

2.4. 默认构造函数/带默认值的构造函数

默认构造函数是调用时可以不提供参数的构造函数,而并一定是不接受任何参数的构造函数。

class human{
private:
	int age;
	string name;
public :
	human(int a=0,string b=""){
		age=a;
		name=b;
	}
};

2.5. 初始化列表

class human{
private:
	int age;
	string name;
public :
	human(int a,string b):age(a),name(b){
	}
};

三、析构函数

对象销毁时自动调用。

3.1.申明与实现

类内申明与实现

class human{
private:
	int age;
	string name;
public :
	~human(){
		//
	}
};

类内申明,类外实现

class human{
private:
	int age;
	string name;
public :
	~human();
};
human::~human(){
		//
	}

3.2.使用

当对象不再在作用域内,或通过delete被删除时调用析构函数。
析构函数是重置变量以及释放动态分配的内存和其他资源的理想场所。

#include<iostream>
using namespace std;

class MyString{
private:
	char*Buffer;
public:
	MyString(const char*ini){
		if(ini!=NULL){
			Buffer=new char[strlen(ini)+1];
			strcpy(Buffer,ini);
		}
		else{
			Buffer=NULL;
		}

	}
	~MyString(){
		cout<<"析构函数调用"<<endl;
		if(Buffer!=NULL){
			delete[] Buffer;
		}

	}
	int GetLnegth(){
		return strlen(Buffer);
	}

	const char*GetString(){
		return Buffer;
	}
};

int main(){
	MyString s1("this is string one");
	cout<<s1.GetLnegth()<<endl;
	cout<<s1.GetString()<<endl;

	return 0;
}
输出:
18
this is string one
析构函数调用
请按任意键继续. . .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值