c++:在类中定义了一个私有成员指针,在进行类的初始化的时候使它指向一个字符串常量?

流光抛却人 2016-11-17 11:23:23
#include<iostream>
#include<string.h>
using namespace std;
class person
{
private:
char *name;
public:
person(const char *name)
{
name=new char;
strcpy(this->name, name);
}
~person( )
{
delete name;
cout<<"person::~person( ) is called"<<endl;
}
void showname( )
{
cout<<*name;
}
};
class date
{
private:
char *birth;
public:
date( )
{

}
date(const char *birth)
{
birth=new char;
strcpy(this->birth, birth);
}
~date( )
{
delete birth;
cout<<"date::~date( ) is called"<<endl;
}
void showbirth( )
{
cout<<*birth;
}
};

class student: public person
{
private:
date birthday;
public:
student(char *name, date birth):person(name)
{
birthday=birth;
}
~student( )
{
cout<<"student::~student( ) is called"<<endl;
}
void show( )
{
cout<<"student's name: ";
person::showname( );
cout<<'\t'<<"student's birth: ";
birthday.showbirth( );
}
};
class professor: public person
{
private:
date birthday;
public:
professor(char *name, date birth):person(name)
{
birthday=birth;
}
~professor( )
{
cout<<"professor::~professor( ) is called"<<endl;
}
void show( )
{
cout<<"professor's name: ";
person::showname( );
cout<<'\t'<<"professor's birth: ";
birthday.showbirth( );
}
};
int main( )
{
date sd("1993"), pd("1948");
student s("wangyu", sd);
professor p("zhaonan", pd);
s.show( );
p.show( );
return 0;
}

错误多多,请大神们指正
...全文
493 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
小灸舞 2016-11-18
  • 打赏
  • 举报
回复
分配空间都是不对的。 name=new char;应该是this->name=new char[strlen(name) + 1]; PS:你还有别的问题,自己再调试下 单步类的实例“构造”或“复制”或“作为函数参数”或“作为函数返回值返回”或“参加各种运算”或“退出作用域”的语句对应的汇编代码几步后,就会来到该类的“构造函数”或“复制构造函数”或“运算符重载”或“析构函数”对应的C/C++源代码处。 VC调试时按Alt+8、Alt+7、Alt+6和Alt+5,打开汇编窗口、堆栈窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应堆栈、内存和寄存器变化,这样过一遍不就啥都明白了吗。 对VC来说,所谓‘调试时’就是编译连接通过以后,按F10或F11键单步执行一步以后的时候,或者在某行按F9设了断点后按F5执行停在该断点处的时候。
paschen 版主 2016-11-17
  • 打赏
  • 举报
回复
birth=new char; 只申请了一个字符的空间,而你是一个字符串,你需要申请一个字符数组

64,633

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧