重载operator=:
解决疑惑的实验:
#include<iostream>
using namespace std;
class myclass
{
public:
myclass(int a=0, int b=0)//有参构造函数
{
this->a = a;
this->b = b;
}
int operator()(int a = 0, int b = 0)
{
return a + b;
}
friend myclass & operator ++(myclass & C1, int)
{
C1.a++;
C1.b++;
return C1;
}
friend ostream& operator<<(ostream& out, const myclass& C)
{
out << C.a << C.b << endl;
return out;
}
private:
int a;
int b;
};
int main()
{
cout << myclass (2, 3) << endl;;
myclass C3(0,0);
cout << C3(2,3) <<endl;
}
实验证明,你不可能通过C3(2,3)这句话使得编译器变得歧义,因为如果你要使用C3(2,3)作为重载了等号的成员函数的时候是不可能同时又作为一个构造函数创建对象了的;使用等号重载了的成员函数了的时候其实要求对象是已经存在了的。
有些时候对&&和||的重载是不可取的:
因为这两个操作符的短路规则,&&条件是只有第一个部分是真的情况下才去执行第二部分;||是第一部分为真的情况下根本不去执行第二部分;这是短路规则;但是在判断一些运算符右侧是一种+或者-的时候,运算符两端都被执行了,而且在判断之前就执行了,这不符合短路规则;例如:if(C1&&C2+C3);
实战Mystring类的设计封装:
#pragma once
#pragma warning(disable:4996)
#include<iostream>
using namespace std;
class Mystring
{
public :
Mystring();//无参数的构造函数
Mystring(int len);//有参数的构造函数,只申请空间,不做输入
Mystring(const char * C);//有参数的构造函数
Mystring(const Mystring& C);//拷贝构造函数
friend ostream& operator <<(ostream& out, Mystring& C1);//友元函数实现的重载<<
friend istream& operator >> (istream& in, Mystring& C);友元函数实现的重载>>
int Length() const;//返回长度
char& operator[](const int i) ;//重载[]
Mystring& operator= (const Mystring& C);//重载等号,使用另一个对象来赋值重载等号
Mystring& operator= (const char* C);//重载等号,使用一个字符串来赋值进行重载
bool operator==(const Mystring& C) const ;//两个对象之间的比较相等
bool operator!=(const Mystring& C) const ;//两个对象之间的比较不等
private:
char * p;//存储串
int length;//长度
};
#include"Mystring.h"
#include<cstring>
ostream& operator <<(ostream& out, Mystring& C1)//友元函数实现的重载<<
{
out << "字符串是:" << C1.p << "长度是:" << C1.length << endl;;
return out;
}
istream& operator >> (istream& in, Mystring& C)友元函数实现的重载>>
{
in >> C.p;
return in;
}
Mystring::Mystring()//无参数的构造函数
{
p = NULL;
length = 0;
}
Mystring::Mystring(const char * C)//有参数的构造函数
{
length = strlen(C);
p = new char[length];
strcpy(p, C);
}
Mystring::Mystring(int len)//有参数的构造函数,只申请空间,不做输入
{
length = len;
this->p = new char[length];
memset(p, 0, sizeof(char)*len);
}
Mystring::Mystring(const Mystring& C)//拷贝构造函数
{
length = C.length;
p = new char[length];
strcpy(p, C.p);
}
int Mystring::Length() const//返回长度
{
return length;
}
char& Mystring::operator[](const int i) //重载[]
{
return this->p[i];
}
Mystring& Mystring::operator=(const Mystring& C)//重载等号,使用另一个对象来赋值重载等号
{
delete this->p;
length = C.length;
this->p = new char[length];
strcpy(this->p, C.p);
return *this;
}
Mystring& Mystring::operator= (const char* C)//重载等号,使用一个字符串来赋值进行重载
{
delete this->p;
length = strlen(C);
this->p = new char[length];
strcpy(this->p, C);
return *this;
}
bool Mystring::operator==(const Mystring& C)const //两个对象之间的比较相等
{
if (C.length != length)return false;
if (strcmp(p, C.p) != 0) return false;
return true;
}
bool Mystring::operator!=(const Mystring& C)const //两个对象之间的比较不等
{
if (C.length != length)return true;
if (strcmp(p, C.p) != 0) return true;
else return false;
}