qq_46007456 2019-12-20 00:32 采纳率: 0%
浏览 389
已采纳

C++定义类的对象的数组为什么不对(主函数刚开始的地方)还有主函数中调用构造函数也错了,为什么

#include <iostream>
#include <fstream>
using namespace std;
class Student
{
public:
    Student(int num,char sex,int score)
    {
        this->num=num;
        this->sex=sex;
        this->score=score;
    }
protected:
    int num;
    char sex;
    int score;
};
int main()
{
    Student stu[3];//此处错误 
    for(int i=0;i<3;i++)
    {
        int num;
        char sex;
        int score;
        cin>>num>>sex>>score;
        stu[i](num,sex,score);//此处错误 
    }
    ofstream outfile("stu.data",ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
//        abort();
    }
    for(int i=0;i<3;i++)
    {
        outfile.write((char*)&stu[i],sizeof(stu[i]));
    }
    outfile.close();
    return 0;
}
  • 写回答

2条回答 默认 最新

  • threenewbee 2019-12-20 09:08
    关注
    #include <iostream>
    #include <fstream>
    using namespace std;
    class Student
    {
    public:
        Student() {}
        Student(int num,char sex,int score)
        {
            this->num=num;
            this->sex=sex;
            this->score=score;
        }
    protected:
        int num;
        char sex;
        int score;
    };
    int main()
    {
        Student stu[3];//此处错误 
        for(int i=0;i<3;i++)
        {
            int num;
            char sex;
            int score;
            cin>>num>>sex>>score;
            stu[i] = Student(num,sex,score);//此处错误 
        }
        ofstream outfile("stu.data",ios::binary);
        if(!outfile)
        {
            cerr<<"open error!"<<endl;
    //        abort();
        }
        for(int i=0;i<3;i++)
        {
            outfile.write((char*)&stu[i],sizeof(stu[i]));
        }
        outfile.close();
        return 0;
    }
    

    问题解决的话,请点下采纳

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已采纳回答 4月23日

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果