#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
#define PATHWAY "star.txt" // 定义文件路径常量
using namespace std;
class Star
{
friend ostream& operator<< (ostream&, const Star&);
private:
char* name; // 明星的姓名
int age; // 明星的年龄
char male; // 明星的性别,'F'代表女性,'M'代表男性
public:
Star(const char* name, int age, char male) // 构造函数,用于初始化 Star 对象
{
this->name = new char[strlen(name) + 1]; // 动态分配内存存储姓名,并复制字符串内容
strcpy(this->name, name);
this->age = age;
this->male = male;
}
Star(const Star& s) // 拷贝构造函数,用于创建新的 Star 对象,并复制已有对象的属性值
{
name = new char[strlen(s.name) + 1]; // 动态分配内存存储姓名,并复制字符串内容
strcpy(name, s.name);
age = s.age;
male = s.male;
}
~Star() // 析构函数,用于释放动态分配的内存
{
delete[] name;
}
};
// 重载输出运算符,用于打印 Star 对象的信息
ostream& operator<< (ostream& out, const Star& s)
{
out << "姓名:" << s.name << endl;
out << "性别:" << s.male << endl;
out << "年龄:" << s.age << endl;
return out;
}
int main()
{
Star s1("陈钰琪", 31, 'F'); // 创建 Star 对象 s1,并初始化属性值
Star s2 = Star("霍思懿", 23, 'M'); // 创建 Star 对象 s2,并初始化属性值
Star s3 = { "鞠婧祎",29,'F' }; // 创建 Star 对象 s3,并初始化属性值
ofstream ofs;
ofs.open(PATHWAY, ios::out | ios::binary | ios::app); // 以追加方式打开文件
// 打开失败则输出错误信息并退出程序
if (!ofs.is_open())
{
cout << "文件打开失败!" << endl;
return 0;
}
ofs.write((const char*)&s1, sizeof(s1)); // 将 s1 写入文件
ofs.close(); // 关闭文件
system("pause"); // 暂停程序执行,等待用户按下任意键继续
return 0;
}
12-13
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)