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 charstrlen(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 charstrlen(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 Student10000; // 调用不带参数的构造函数10000次

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

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

Student s3;

s3 = s1; // 运算符重载

复制代码
return 0;

}

相关推荐
JosieBook2 小时前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
Huangjin007_3 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
敲上瘾4 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
炸膛坦客5 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
小飞在努力6 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
ShineWinsu6 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog
落羽的落羽7 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
叼烟扛炮8 小时前
[LangChain] 学习笔记(24):流式不改总耗时,只改「多久看到第一个字」——实测差 3 倍
笔记·学习·langchain
会编程的吕洞宾8 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤8 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql