|
小白一个,处于自学阶段,跟着本科教材上的示例碰到的问题。
编译器:VS2022
教材:《Visual C++实用教程(第三版)》
问题:
1.在重载<<与>>运算符时,示例代码 os.write((char*)&stu.fScore, 4) 中(char*)&stu.fScore 不太明白为什么要这么写,去掉(char*)&时会报错,求大佬帮忙解答一下为什么要这么写;

2.示例代码中定义了一个class CStudent(char* name, char* id, float score),并在main函数中CStudent* one = new CStudent("", ""),这时候编译器报错参数列表不匹配,个人尝试将main函数代码改成CStudent* one = new CStudent("", "",0),编译器不报错了,程序也能正常跑。
是否可以理解为自己定义的 class CA(参数1,参数2,...,参数n),在用new进行分配内存时应写为 CA* a=new CA(参数1默认值,参数2默认值,...,参数n默认值),求大佬帮忙解答一下我这么理解是否正确,如果理解有误还麻烦帮忙指导一下如何进行这个new操作;
书本上的示例代码如下:
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
//文件操作综合使用:<<,>>的重载,文件流的读与写
#include<iomanip>
#include<fstream>
class CStudent
{
public:
CStudent(char* name, char* id, float score);
friend istream& operator>>(istream& is, CStudent& stu);
friend ostream& operator<<(ostream& os, CStudent& stu);
void print();
private:
char strName[10];
char strID[10];
float fScore;
};
CStudent::CStudent(char* name, char* id, float score)
{
strncpy(strName, name,10); //字符数组的赋值别用=,用strncpy比strcpy更安全
strncpy(strID, id, 10);
fScore = score;
}
void CStudent::print()
{
cout << "学生信息如下:" << endl;
cout << "姓名:" << strName << endl;
cout << "学号:" << strID << endl;
cout << "成绩:" << fScore << endl;
}
ostream& operator<<(ostream& os, CStudent& stu)
{
os.write(stu.strName, 10);
os.write(stu.strID, 10);
os.write((char*)&stu.fScore, 4); //float类型占用4字节,但不明白为什么要这么写。。。
return os;
}
istream& operator>>(istream& is, CStudent& stu)
{
char name[10],id[10];
is.read(name, 10);
is.read(id, 10);
is.read((char*)&stu.fScore, 4);
strncpy(stu.strName, name, 10);
strncpy(stu.strID, id, 10);
return is;
}
void main()
{
CStudent stu1("LiMing", "99001", 88);
CStudent stu2("ZhangSan", "99002", 86);
CStudent stu3("HanMeiMei", "99003", 92);
CStudent stu4("WangWei", "99004", 90);
CStudent stu5("DingNing", "99005", 91);
fstream file1;
file1.open("student.txt", ios::out | ios::in | ios::binary);
file1 << stu1 << stu2 << stu3 << stu4 << stu5;
CStudent* one = new CStudent("", "",0);
const int size = sizeof(CStudent);
file1.seekp(size * 4);
file1 >> *one;
one->print();
file1.seekp(size * 1);
file1 >> *one;
one->print();
file1.seekp(size * 2, ios::cur);
file1 >> *one;
one->print();
file1.close();
delete one;
}
|
上一篇: 代码移植,语法不会了。。。求助。。。。下一篇: 如何获取文件系统的目录个数
|