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

最近在写一个小程序时,主要是文件信息的读取。

在程序中定义了类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++中的指针真难伺候啊

 

原文链接: https://www.cnblogs.com/young525/archive/2012/03/24/5873857.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/45108

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午9:41
下一篇 2023年2月8日 下午9:42

相关推荐