关于网友提出的“ 操作符'=' 重定义?”问题疑问,本网通过在网上对“ 操作符'=' 重定义?”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 操作符'=' 重定义?
描述:
//this is String.cpp
#include
class String
{
private:
char * m_pCh;
int len;
static int num_strings;//number of string
static const int CINLIM=80;//cin input limit
public:
String();
String(const char * s);
String(const String &s);
int Length()const{return len;};
String & operator=(const String &s);
String & operator=(const char* s);
char & operator[](int i);
const char & operator[](int i)const;
friend bool operator<(const String &s1,const String & s2);
friend bool operator>(const String & s1,const String & s2);
friend bool operator==(const String & s1,const String & s2);
static int HowMany();
};
String & String::operator=(const char *s)
{
delete[] m_pCh;
len = strlen(s);
m_pCh=new char[len+1];
strcpy(m_pCh,s);
return *this;
}
main.cpp里仅包含String.cpp,构建了一个String对象
解决方案1: 请问楼上,放在cpp和放在.h中有什么区别呢?
解决方案2:String & String::operator=(const char *s)
{
delete[] m_pCh;
len = strlen(s);
m_pCh=new char[len+1];
strcpy(m_pCh,s);
return *this;
}
放到cpp中,不要放在头文件中
以上介绍了“ 操作符'=' 重定义?”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/2196490.html