林锐 C++ 问题!:(

linestyle 2005-08-11 03:54:50
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operator =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};


String::~String(void) // 3分
{
delete [] m_data;
// 由于m_data是内部数据类型,也可以写成 delete m_data;
}

// String的普通构造函数
String::String(const char *str) // 6分
{
if(str==NULL)
{
m_data = new char[1]; // 若能加 NULL 判断则更好
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, str);
}
}

// 拷贝构造函数
String::String(const String &other) // 3分
{
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data);
}

// 赋值函数
String & String::operator =(const String &other) // 13分
{
// (1) 检查自赋值 // 4分
if(this == &other)
return *this;

// (2) 释放原有的内存资源 // 3分
delete [] m_data;

// (3)分配新的内存资源,并复制内容 // 3分
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data);

// (4)返回本对象的引用 // 3分
return *this;
}

------------为什么:
// 拷贝构造函数
String::String(const String &other) // 3分
{
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data);
}

上面可以访问other.m_data,他应该是私有变量啊:(,请同志们相告:)
...全文
115 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
linestyle 2005-08-12
  • 打赏
  • 举报
回复
谢谢你啊:)
darkstar21cn 2005-08-11
  • 打赏
  • 举报
回复
因为String ()是一个成员函数呀,这是意义是对于一个类的,并非一个实例。

这个问题已经有很多人问过了

64,662

社区成员

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

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