C++ 对象

类与对象的封装

一个类的基本构造

// class 关键字定义类
class Student
{
	// 属性
	// 方法
};

访问修饰符

访问修饰符作用域
public类内可以访问,类外也可以访问,公共权限,可以inherit,类外可以读写
protected受保护权限,类内可以访问,类外不可以访问,可以inherit,类外不可读写
private私有权限,类内可以访问,类外不可以访问,不可以inherit,类外不可读写

构造函数与析构函数

编译器在通常情况下,一般会给一个类默认提供三个函数

  • 无参构造函数
  • 析构函数
  • 拷贝构造函数

构造函数

  • 无返回值,不用写void关键字
  • 可以有参数,可以重载
  • 函数名称与类名相同
  • 程序在调用对象时会自动调用函数,无需手动调用,而且一个对象有且只有一次会调用构造函数
class Student
{
	public :
		Student()
		{
		}
		// 构造函数可以重载
		Student(int id,string name)
		{
		}
};
构造函数的调用
#include <iostream>
#include <string>

using namespace std;

class Student
{
private :
	int id;
	string name;
public :

	// 默认构造函数
	Student()
	{
		cout << "默认(无参构造函数)" << endl;
	}

	// 有参构造函数
	Student(int id, string name)
	{
		this->id = id;
		this->name = name;

		cout << "有参构造函数, id:" << this->id << "name:" << this->name << endl;
	}

	// 拷贝构造函数
	Student(const Student& student)
	{
		this->id = student.id;
		this->name = student.name;

		cout << "(引用类型为参数叫拷贝构造参数)有参构造函数, id:" << this->id << "name:" << this->name << endl;
	}
};

int main()
{	

	// 括号调用
	Student s1;		// 调用无参构造函数时不能加括号,如果加了编译器认为这是一个函数声明
	Student s2(1, "Davi");
	Student s3(s2);

	// 显示法
	Student ss1 = Student();
	Student ss2 = Student(1,"Davi");
	Student ss3 = Student(ss2);

	//隐式转换法
	Student sss2 = ss2;

	// 不能利用拷贝构造函数初始化匿名函数

	system("pause");
	return 0;
}

析构函数

  • 析构函数,没有返回值也不写void
  • 函数名称与类名相同,在名称前面加上符号~
  • 函数不能有参数,所以也不能有重载
  • 程序在对象销毁前会自动调用析构函数,无须手动调用,一个对象有且只有一次会调用析构函数
class Student
{
	public :
		~ Student()
		{
		}
};

构造函数里面的拷贝函数类型

拷贝函数在什么时候会被调用

  • 使用一个创建完毕的对象来初始化一个新对象时
  • 值传递的方式给函数参数传参
  • 以值的方式返回局部对象
#include <iostream>

using namespace std;

// 定义一个类
class Student
{
	int id;
	string name;

public :
	
	// 默认构造函数
	Student()
	{	
		this->id = 0;
		this->name = "";
		cout << "默认构造无参函数" << endl;
	}

	// 有参构造函数
	Student(int id, string name)
	{
		this->id = id;
		this->name = name;
		cout << "有参构造函数" << endl;
	}

	// 拷贝构造函数
	Student(const Student& student)
	{
		cout << "拷贝构造函数" << endl;
		this->id = student.id;
		this->name = student.name;
	}
};

/// <summary>
/// 当一个对象被当作一个参数放进函数中时
/// 其实就相当于这个对象被复制拷贝一份
/// </summary>
void test01(Student s)
{
	cout << (int)&s << endl;
}

/// <summary>
/// 在函数内部返回一个对象,其实也是拷贝了一份对象return出去
/// </summary>
/// <returns></returns>
Student test02()
{
	Student s;
	cout << "函数内部对象的地址:" << (int)&s << endl;
	return s;
}

int main()
{	
	Student s;
	test01(s);
	cout << "---------------------------" << endl;
	cout << "test02返回的函数地址" << (int)&test02() << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值