关于等号运算符的重载
代码如下:
#include <iostream>
using namespace std;
class CString
{
public:
CString(char *m="");
~CString();
bool operator ==(const CString &b);
private:
char *str;
};
bool CString::operator ==(const CString &b)
{
char *p,*q;
p=str;
q=b.str;
while (p!='\0'||q!='\0') //在这里如何判断字符串结束的标志?即如何退出循环?我这里写的条件陷入了死循环。
{
if (*p==*q)
{
p++;
q++;
}
else
return false;
}
return true;
}
CString::CString(char *m)
{
str=new char[strlen(m)+1];
if (str==NULL)
{
cerr<<"error";
exit(1);
}
strcpy(str,m);
}
CString::~CString()
{
delete []str;
}
void main()
{
CString s1("abc"),s2("abc");
if (s1==s2)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
而且测试的结果是false,显然是错的。
#include <iostream>
using namespace std;
class CString
{
public:
CString(char *m="");
~CString();
bool operator ==(const CString &b);
private:
char *str;
};
bool CString::operator ==(const CString &b)
{
char *p,*q;
p=str;
q=b.str;
while (p!='\0'||q!='\0') //在这里如何判断字符串结束的标志?即如何退出循环?我这里写的条件陷入了死循环。
{
if (*p==*q)
{
p++;
q++;
}
else
return false;
}
return true;
}
CString::CString(char *m)
{
str=new char[strlen(m)+1];
if (str==NULL)
{
cerr<<"error";
exit(1);
}
strcpy(str,m);
}
CString::~CString()
{
delete []str;
}
void main()
{
CString s1("abc"),s2("abc");
if (s1==s2)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
而且测试的结果是false,显然是错的。
...全文
相关推荐
等号运算符重载
等号运算符重载 函数重载 c++代码 开发工具:VS2010
C++运算符重载详解[项目代码]
本文详细介绍了C++中运算符重载的概念、基本格式及两种实现方法(类内重载和类外重载)。通过具体代码示例,展示了二元运算符(如+、-、*、/等)和一元运算符(如++、<<等)的重载方式,并解释了前置与后置运算符的区别。此外,文章还探讨了等号运算符重载的必要性,以及浅拷贝与深拷贝的问题,强调了手工编写拷贝构造函数和等号运算符重载函数的重要性,以避免内存管理错误。
等号操作符使用陷阱实例
举例说明等号操作符的使用方法,避免初学者采坑;
Polyop:C++14 的可覆盖通用运算符重载
波利奥普 C++14 的可覆盖通用运算符重载 什么是波利奥普? C++ 支持运算符重载,当它们与用户定义的类型一起使用时,允许用户为该运算符指定自定义语义。 例如: struct foo {}; std::ostream& operator <<( std::ostream& os , const foo& ) { return os << " a foo! " ; } 该规范使用函数重载工作,因此语义是固定和唯一的。 当然,所有 C++ 基本类型和库类型都有自己的运算符重载,例如1 + 1是允许的,因为存在operator+(int,int)重载。 但是,如果默认操作符语义不符合我们的要求怎么办? 这就是 Polyop 发挥作用的地方。 考虑常见的浮点比较问题: float a = 2 . 0f , b = 3 . 0f assert ( a + a
运算符重载函数(链表类).cpp
运算符重载函数(链表类).cpp


