对象:
1.创建对象的方法:
Human h1;--->>第一种
Human *h2 = new Human();----->>第二种
2.创建默认构造函数:
class Human{
Human();
}
在外面构造
Human::Human(){
.......
}
3.可以在默认的构函数上添加参数来构造有参的构造函数
4.深拷贝:
当类中有需要开辟内存的时候要深拷贝(数组)
char *data;
data = new char[length + 1]; // 分配新内存
strcpy(data, other.data); // 复制内容
===========================================深拷贝
5.赋值构造函数:
class Human {
private:
std::string name;
int age;
public:
// 拷贝赋值运算符声明
Human& operator=(const Human &other);
};
// 拷贝赋值运算符定义
Human& Human::operator=(const Human &other) {
if (this != &other) { // 防止自赋值
name = other.name;
age = other.age;
}
return *this; // 返回当前对象的引用
}