文章目录
一 . "++"(自增)运算符重载二 . "="(赋值)运算符重载
一 . “++”(自增)运算符重载
#include <iostream>
using namespace std
;
class MyInteger
{
friend ostream
& operator<<(ostream
&cout
, MyInteger myint
);
private:
int m_Num
;
public:
MyInteger()
{
m_Num
= 0;
}
MyInteger
& operator++(){
m_Num
++;
return *this;
}
MyInteger
operator++(int){
MyInteger temp
= *this;
m_Num
++;
return temp
;
}
};
ostream
& operator<<(ostream
&cout
, MyInteger myint
){
cout
<<myint
.m_Num
;
return cout
;
}
void test01(){
MyInteger int01
;
cout
<<"测试前置递增"<<endl
;
cout
<<++int01
<<endl
;
cout
<<int01
<<endl
;
}
void test02(){
MyInteger int02
;
cout
<<"测试后置递增"<<endl
;
cout
<<int02
++<<endl
;
cout
<<int02
<<endl
;
}
int main(){
test01();
test02();
system("pause");
}
二 . “=”(赋值)运算符重载
#include <iostream>
using namespace std
;
class Book
{
private:
int *m_Num
;
public:
Book(int num
){
m_Num
= new int(num
);
}
~Book(){
if(m_Num
!= NULL){
delete m_Num
;
m_Num
= NULL;
}
}
void showNum(){
cout
<<*m_Num
<<endl
;
}
Book
& operator=(Book
&book
){
if(m_Num
!= NULL){
delete m_Num
;
m_Num
= NULL;
}
m_Num
= new int(*book
.m_Num
);
return *this;
}
};
int main(){
Book
b1(1);
Book
b2(2);
Book
b3(3);
cout
<<"赋值前"<<endl
;
b1
.showNum();
b2
.showNum();
b3
.showNum();
b3
= b2
= b1
;
cout
<<"赋值后"<<endl
;
b1
.showNum();
b2
.showNum();
b3
.showNum();
}
转载请注明原文地址:https://tech.qufami.com/read-11880.html