C++_课堂笔记_构造与析构

#include

#include

using namespace std;

struct Date

{

int y, m, d;

void setDate(int, int, int);

Date(int yy, int mm, int dd) {y = yy, m = mm, d = dd;}

};

class Student

{

private:

char* name;

Date birthday;

public:

// 如果没写不带参数的构造函数,系统会提供一个不带参数的构造函数,称为缺省构造函数,或者是拷贝构造函数

Student(const Student&); // 拷贝构造函数,当有new和delete的时候要写

Student():birthday(2000, 3, 4) {} // 不带参数的构造函数

Student(char*, int, int, int);

~Student() {delete []name;} // 与构造函数成对出现

};

Student::Student & operator = (const Student &s1) // 运算符重载函数

{

name = new char[strlen(s1.name) + 1];

strnpy(name, s1.name, strlen(s1.name));

birthday = s1.birthday;

return *this;

}

Student::Student(const Student &s1) // 拷贝构造函数

:birthday(s1.birthday) // 初始化

{

// name = s1.name; // 错误

name = new char[strlen(s1.name) + 1];

// name = s1.name; 错误,没用到新开辟的空间

strncpy(name, s1.name, strlen(s1.name));

}
:
birthday(y, m, d) // 初始化

复制代码
{   

// name = p; 不好,指针会改变   

// name = new char\[sizeof§\]; // 指针的大小,一般为8个字节,但不是字符串的长度   

name = new char\[strlen§ + 1\]; // 多一个位置存放'\\0'   

strncpy(name, p, strlen§);   

};

void print(Student s)

{

cout << s,name << endl; // error,私有的,不能访问

}

int main()

{

const char p = "zhangsan";
Student s1((char
)p, 2000, 3, 4); // 强制类型转换

// Student *s;

// s = new Student[10000]; // 调用不带参数的构造函数10000次

Student s2(s1); // 调用拷贝构造函数

// print(s1); // 也会调用拷贝构造函数

Student s3;

s3 = s1; // 运算符重载

复制代码
return 0;

}

相关推荐
汇能感知2 小时前
摄像头模块在运动相机中的特殊应用
经验分享·笔记·科技
阿巴Jun3 小时前
【数学】线性代数知识点总结
笔记·线性代数·矩阵
茯苓gao3 小时前
STM32G4 速度环开环,电流环闭环 IF模式建模
笔记·stm32·单片机·嵌入式硬件·学习
是誰萆微了承諾3 小时前
【golang学习笔记 gin 】1.2 redis 的使用
笔记·学习·golang
皮皮林5514 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
利刃大大4 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
weixin_456904274 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_4 小时前
异步编程CompletionService
java
DKPT4 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue4 小时前
Guava中常用的工具类
java·guava