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;

}

相关推荐
超级种码12 分钟前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
甜鲸鱼20 分钟前
【Spring AOP】操作日志的完整实现与原理剖析
java·spring boot·spring
狗头大军之江苏分军24 分钟前
年底科技大考:2025 中国前端工程师的 AI 辅助工具实战盘点
java·前端·后端
杨忆25 分钟前
构建自己的开发工作台MFC
数据库·c++·mfc
wadesir38 分钟前
C++非对称加密实战指南(从零开始掌握RSA加密算法)
开发语言·c++
一 乐1 小时前
酒店客房预订|基于springboot + vue酒店客房预订系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
计算机毕设指导61 小时前
基于Spring Boot的防诈骗管理系统【源码文末联系】
java·spring boot·后端·spring·tomcat·maven·intellij-idea
七禾页丫1 小时前
面试记录12 软件(c++)工程师
c++·面试·职场和发展
a程序小傲1 小时前
饿了吗Java面试被问:Redis的持久化策略对比(RDBVS AOF)
java·redis·面试
我家领养了个白胖胖1 小时前
MCP模型上下文协议 Model Context Protocol & 百度地图MCP开发
java·后端·ai编程