【无标题】类 构造函数 析构函数 五一学习C++学习记录

【无标题】类 构造函数 析构函数 五一学习C++学习记录,第1张

目录

什么是类?

什么是对象?

构造函数的作用

构造函数的特点

构造函数的种类

默认构造函数

什么时候调用拷贝构造函数

        心得:


什么是类?

类是面向对象语言的程序设计中的概念,是面向对象编程的基础。

  面向对象编程,最重要的第一个概念:类

“人类”是一个抽象的概念,不是具体的某个人。

“类”,是看不见,摸不着的,是一个纯粹的概念.

“类”,是一种特殊的“数据类型”,不是一个具体的数据。

注意:类, 和基本数据类型(char/int/short/long/long long/float/double)不同

类的构成:方法和数据

什么是对象?

对象,是一个特定“类”的具体实例。

一般地,一个对象,就是一个特殊的变量,但是有跟丰富的功能和用法。

#include 
#include 
#include 

using namespace std;

//定义一个"人类"
class Human {
public://公有的,对外的
	void eat(); //方法,成员函数
	void sleep();
	void play();
	void work();

	string getName();
	int getAge();
	int getSalary();

private:
	string name;
	int age;
	int salary;
};

void Human::eat() {
	cout << "吃炸鸡,喝啤酒!" << endl;
}

void Human::sleep() {
	cout << "我正在睡觉!" << endl;
}

void Human::play() {
	cout << "我在唱歌!" << endl;
}

void Human::work() {
	cout << "我在工作..." << endl;
}

string Human::getName() {
	return name;
}

int Human::getAge() {
	return age;
}

int Human::getSalary() {
	return salary;
}

int main(void){
	//使用已经定义好的类Human来创建一个对象 h1
	Human h1;

	h1.eat();
	h1.play();
	h1.sleep();


	Human* p;
	p = &h1;

	p->eat();
	p->play();
	p->sleep();


	system("pause");
	return 0;
}
构造函数的作用

在创建一个新的对象时,自动调用的函数,用来进行“初始化”工作:

对这个对象内部的数据成员进行初始化。

构造函数的特点
  1. 自动调用(在创建新对象时,自动调用)
  2. 构造函数的函数名,和类名相同
  3. 构造函数没有返回类型
  4. 可以有多个构造函数(即函数重载形式)

构造函数的种类

默认构造函数

自定义的构造函数

拷贝构造函数

赋值构造函数

默认构造函数

没有参数的构造函数,称为默认构造函数。

什么时候调用拷贝构造函数
  1. 调用函数时,实参是对象,形参不是引用类型

   如果函数的形参是引用类型,就不会调用拷贝构造函数

  1. 函数的返回类型是类,而且不是引用类型
  2. 对象数组的初始化列表中,使用对象。
//析构函数的作用: 对象销毁前,做清理工作
//比如:如果在构造函数中,使用 new 分配了内存,
//就需在析构函数中用 delete 释放
#include 
#include 
#include 

#define ADDR_LEN  64
using namespace std;

//定义一个"人类"
class Human {
public:
	Human();//手动定义的默认构造函数
	Human(int age, int salary);//自定义的(重载)构造函数
	Human(const Human& other);//手动定义的拷贝构造函数
	Human& operator=(const Human& other);//手动定义的赋值构造函数
	~Human();//手动定义的析构函数
	//... ...
private:
	string name = "Unknown";//类内初始化
	int age = 18;//类内初始化
	int salary = 25000;
	char* addr;
};
Human::Human() {
	string name = "Macro";
	int age = 22;
	int salary = 30000;
	
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, "China");//深度拷贝
	cout << "调用默认构造函数" << endl;
}

Human::Human(int age, int salary) {

}

Human::Human(const Human& other) {

}

Human& Human::operator=(const Human& other) {
	return *this;
}

Human::~Human() {
	cout << "调用析构函数" << this << endl;//用于打印测试信息
	delete addr;
}

void test() {
	Human h1;

	{
		Human h2;
	}

	cout << "test()结束" << endl;
}

int main(void) {

	test();

	system("pause");
	return 0;
}
        心得:

        五一的学习记录就写到这里,突然发现记录自己的学习历程是一件很艰难的事情,在记录的过程中,会发现自己根本不知道如何开始记录,完全没有头绪,虽然今天只是简单的将自己写好的代码粘贴复制,并没有做到深刻理解,但是现在我知道下一次我来到这里的时候,我的学习记录会写的深刻,虽然别人可能看不懂,但我会一步一步的做出优化,将自己在学习过程中的问题记录下来,以及如何解决的,这些是最宝贵的,今天先到这儿吧!

最后,欢迎大佬指点,学习经验.

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/793541.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存