注册 登录
编程论坛 C++教室

这个是关于文件的C++,有个小问题,求解决

mofachaoshao 发布于 2013-06-23 10:41, 483 次点击
程序代码:
#include <fstream.h>
#include <iostream.h>
//定义小学生类
class Primary
{
public:
    int chin; //语文成绩
    int math; //数学成绩
    Primary(int c, int m)
    {
        chin = c;
        math = m;
    }
    //从【in2.dat】二进制文件中,读取语文和数学成绩
    void loadData()
    {
        fstream f("in2.dat",ios::in|ios::binary);
        f.read((char*)&chin,sizeof(int));
        f.read((char*)&math,sizeof(int));
        f.close();
    }

 };
//定义中学生类
class Middle: public Primary
{

   double ave;
public:
    int phys;  //物理成绩
    int chem;  //化学成绩
    Middle(int c, int m, int ph, int ch):Primary(c,m)
    {
        phys= ph;
        chem = ch;
    }
    //计算平均成绩函数,考生需要填写此函数
    double calcAve()
    {
    return (chin+math+phys+chem)/4.0;
    }
    //保存平均成绩到【out2.dat】中,用文本存储
    void saveData()
    {
        fstream f("out2.dat",ios::out);
        f<<calcAve()<<endl;
        f.close();
        cout<<"Success"<<endl;
    }
};
//考生需要在main函数中编写代码,用中学生类创建对象进行相关处理。
void main ()
{
   Primary p1;
   p1.loadData();
   int  x=p1.chin ;
   int  y=p1.math ;
   int p=75,q=86;
   Middle m1(x,y,p,q);
   m1.calcAve();
   m1.saveData();

}
错误之处:Compiling...
prog2.cpp
C:\Users\Administrator\Desktop\1234\prog2.cpp(61) : error C2512: 'Primary' : no appropriate default constructor available
执行 cl.exe 时出错.

prog2.obj - 1 error(s), 0 warning(s)
1 回复
#2
好聚好散2013-06-23 11:14
在派生类的构造函数里,会自动调用父类的缺省构造函数,由于你自己提供了构造函数 所以系统将不会再提供默认的构造函数也就是default constructor



class Primary
{
public:
    int chin; //语文成绩
    int math; //数学成绩
    Primary(int c, int m)
    {
        chin = c;
        math = m;
    }
    //从【in2.dat】二进制文件中,读取语文和数学成绩
    void loadData()
    {
        fstream f("in2.dat",ios::in|ios::binary);
        f.read((char*)&chin,sizeof(int));
        f.read((char*)&math,sizeof(int));
        f.close();
    }

    Primary(){}
};
1