您的位置:首页 > 其它

构造函数中指针参数的初始化

2012-03-24 15:51 155 查看
最近在写一个小程序时,主要是文件信息的读取。

在程序中定义了类Tperson

class Tperson

{

public:

Tperson(string newName=NULL ,int newAge=0);

virtual~Tperson();

private:

string name;

int age;

public:

void SetName(string newName);

voidSetAge(int newAge);

stringGetName();

intGetAge();

};

person::Tperson(string newName,int newAge)

{

name=newName;

age=newAge;

}

Tperson::~Tperson()

{

}

int Tperson::GetAge()

{

returnage;

}

string Tperson::GetName()

{

returnname;

}

void Tperson::SetAge(int newAge)

{

age=newAge;

}

void Tperson::SetName(string newName)

{

name=newName;

}

然后定义两个类数组

Tpersonap1[3]={Tperson("wang",26),Tperson("zhao",29),Tperson("huang",21)};

Tperson ap2[3];

主程序如下

int main(int argc,char*argv[])

{

inti;

ofstreamofile;

ofile.open("data.text",ios::out);

if(!ofile)

{

cout<<"can'topen output file"<<endl;

return-1;

}

for(i=0;i<3;i++)

{

ofile.write((char*)&ap1[i],sizeof(ap1[i]));

}

ofile.close();

ifstreamifile;

ifile.open("data.text",ios::in|ios::binary);

if(!ifile)

{

cout<<"can'topen input file"<<endl;

return-1;

}

for(i=0;i<3;i++)

{

ifile.read((char*)&ap2[i],sizeof(ap2[i]));

}

ifile.close();

for(i=0;i<3;i++)

{

cout<<"nameof person "<<i+1<<" is"<<ap2[i].GetName()<<endl;

cout<<"ageof person "<<i+1<<" is"<<ap2[i].GetAge()<<endl;

}

return0;

}

编译完全通过,可是一运行就出错,内存不能读。纠结好了好久,这可是按书上面的例子编写的。

最后实在不行了,一行一行代码的查找,发现出错在Tperson ap2[3]上。因为这个类是没有初始化的,只能调用默认构造函数,可是默认构造函数中的string newName=NULL,这样表面上看是给了默认值,实际上该参数仍然是不定的。

将stringnewName=NULL改为stringnewName=””。

重新编译,运行OK.。

C++中的指针真难伺候啊
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐