读书人

这个构造函数是咋回事赋值失败

发布时间: 2012-06-16 20:34:32 作者: rapoo

这个构造函数是怎么回事,赋值失败

C/C++ code
class student{private:    int number;    string name;    string sex;    string address;    float English,physic,math,eletron;public:    student(int  =0,string=" ",string=" ",string=" ",float=0.0,float=0.0,float=0.0,float=0.0);    friend ostream & operator <<(ostream &,student &);};student::student(int num,string nam,string se,string add,float eng,float phy,float mat,float elet){    number=num;    name=nam;    sex=se;    address=add;    English=eng;    physic=phy;    math=mat;    eletron=elet;} int main(){    const int h=4;    int i,j=1;        student stu[h]={(6004327,"张飞","男","北京路58号",80,75,91,78),        (6004121,"关羽","女","天津路17号",88,85,91,68),        (6004118,"刘备","女","上海路27号",98,87,81,86),        (6004231,"赵云","男","广州路38号",73,82,93,92),    };        return 0;}



代码来自一个同学的,我挑出部分代码来调试,

发现调试的时候,

在构造函数里设置断点,各个成员赋值没有成功,

难道用错了??


汗,基础不好啊



[解决办法]
C/C++ code
#include<iostream>   #include<string>  using namespace std;class student{private:    int number;    string name;    string sex;    string address;    float English,physic,math,eletron;public:    student(int ,string,string,string,float,float,float,float);    friend ostream & operator <<(ostream &,student &);};student::student(int num=0,string nam="",string se=" ",string add="",float eng=0.0,float phy=0.0,float mat=0.0,float elet=0.0){    number=num;    name=nam;    sex=se;    address=add;    English=eng;    physic=phy;    math=mat;    eletron=elet;}ostream & operator <<(ostream &outs,student &obj){    cout<<obj.number<<endl;    cout<<"Name "<<obj.name<<endl;    cout<<"Sex "<<obj.sex<<endl;    cout<<"Address "<<obj.address<<endl;    cout<<"Eng="<<obj.English<<" phy="<<obj.physic<<" math="<<obj.math<<" ele"<<obj.eletron<<endl;    cout<<endl;    return outs;}int main(){    const int h=4;    int i,j=1;    student stu[h]={student(6004327,"张飞","男","北京路58号",80,75,91,78),        student(6004121,"关羽","女","天津路17号",88,85,91,68),        student(6004118,"刘备","女","上海路27号",98,87,81,86),        student(6004231,"赵云","男","广州路38号",73,82,93,92),    };    for (i=0;i<4;i++)    {        cout<<stu[i];    }    return 0;}
[解决办法]
student stu={6004327,"张飞","男","北京路58号",80,75,91,78};
这种初始化方式必须同时满足下面两个条件:
1. 所有的成员变量必须是public
2. 没有自己定义构造函数

由于通常意义上struct,都很自然的满足了上面两个条件,所以struct也可以那样赋值。

读书人网 >C++

热点推荐