下面是一些 C++ 運算符重載示例,包括算術運算符、賦值運算符、邏輯運算符、成員運算符、關系運算符等等,這些都是使用頻率較高的幾個運算符重載案例。
?? 所有示例代碼均存放于 GitHub: getiot/cpp-courses/operator_overloading 。
示例 1:一元運算符重載
一元運算符即只對一個操作數(shù)進行操作的運算符,例如:!obj
、-obj
、++obj
、obj++
或 obj--
等等。
下面示例將對負號(-
)進行重載:
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 到無窮
int inches; // 0 到 12
public:
// 構造函數(shù)
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// 顯示距離
void displayDistance() {
cout << "F: " << feet << ", I: " << inches << endl;
}
// 重載負運算符 ( - )
Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main(void)
{
Distance d1(1, 10), d2(-5, 110);
-d1; // 取相反數(shù)
d1.displayDistance(); // 距離 D1
-d2; // 取相反數(shù)
d2.displayDistance(); // 距離 D2
return 0;
}
編譯并運行以上示例,輸出結果如下:
F: -1, I: -10
F: 5, I: -110
示例 2:二元運算符重載
二元運算符即需要兩個參數(shù)的運算符,例如:加運算符(+
)、減運算符(-
)、乘運算符(*
)、除運算符(/
)。
下面示例將重載加運算符(+
):
#include <iostream>
using namespace std;
class Box
{
double length; // 長度
double width; // 寬度
double height; // 高度
public:
Box () {
length = 0.0;
width = 0.0;
height = 0.0;
}
Box (double a, double b ,double c)
{
length = a;
width = b;
height = c;
}
double getVolume(void)
{
return length * width * height;
}
// 重載 + 運算符,用于把兩個 Box 對象相加
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.width = this->width + b.width;
box.height = this->height + b.height;
return box;
}
};
int main(void)
{
Box b1(5.0, 4.0, 3.0);
Box b2(6.0, 5.0, 4.0);
Box b3;
cout << "Volume of b1 : " << b1.getVolume() << endl;
cout << "Volume of b2 : " << b2.getVolume() << endl;
// 把兩個對象相加,得到 Box3
b3 = b1 + b2;
// Box3 的體積
cout << "Volume of b3 : " << b3.getVolume() << endl;
return 0;
}
使用 g++ main.cpp && ./a.out
命令編譯運行以上示例,輸出結果如下:
Volume of b1 : 60
Volume of b2 : 120
Volume of b3 : 693
示例 3:關系運算符重載
C++ 允許重載任何一個關系運算符(例如 < 、 > 、 <= 、 >= 、 == 等),重載后的關系運算符可用于比較類的對象。許多 C++ 內置的數(shù)據(jù)類型也都支持各種關系運算符。
下面示例將重載小于符(<):
#include <iostream>
using namespace std;
class Rect
{
private:
double width;
double height;
public:
Rect(double a, double b)
{
width = a;
height = b;
}
double area() {
return width * height;
}
// 重載小于運算符 ( < ), 按照面積比大小
bool operator<(Rect& that)
{
return this->area() < that.area();
}
};
int main()
{
Rect r1(3.0, 5.0), r2(3.5, 4.5);
cout << "Area of r1 = " << r1.area() << endl;
cout << "Area of r2 = " << r2.area() << endl;
if ( r1 < r2 )
cout << "r1 is less than r2" << endl;
else
cout << "r1 is large than r2" << endl;
return 0;
}
編譯運行以上代碼,輸出結果如下:
Area of r1 = 15
Area of r2 = 15.75
r1 is less than r2
示例 4:輸入/輸出運算符重載
C++ 使用流提取運算符(>>
)和流插入運算符(<<
)來輸入和輸出內置的數(shù)據(jù)類型,同時也允許重載 >>
和 <<
來操作對象等用戶自定義的數(shù)據(jù)類型。
可以把運算符重載函數(shù)聲明為類的友元函數(shù),這樣就可以不用創(chuàng)建對象而直接調用函數(shù)。
#include <iostream>
using namespace std;
class Rect
{
public:
double width;
double height;
Rect() {
width = 0;
height = 0;
}
Rect(double a, double b )
{
width = a;
height = b;
}
double area() {
return width * height;
}
friend std::ostream &operator<<(std::ostream &output, Rect &r)
{
output << "width: " << r.width << ", ";
output << "height: " << r.height << ", ";
output << "area: " << r.area();
return output;
}
friend std::istream &operator>>(std::istream &input, Rect &r)
{
input >> r.width >> r.height;
return input;
}
};
int main()
{
Rect r1(3.0, 4.0), r2(6.0, 8.0), r3;
cout << "Enter the value of object: \n";
cin >> r3;
cout << "r1: " << r1 << endl;
cout << "r2: " << r2 << endl;
cout << "r3: " << r3 << endl;
return 0;
}
編譯和運行以上示例,輸出結果如下:
Enter the value of object:
2 3
r1: width: 3, height: 4, area: 12
r2: width: 6, height: 8, area: 48
r3: width: 2, height: 3, area: 6
示例 5:++ 和 – 運算符重載
遞增運算符(++
)和遞減運算符(--
)是 C++ 語言中兩個重要的一元運算符,包括前綴和后綴兩種用法。
下面示例將演示如何重載前綴自增(++obj
)和后綴自減運算符(obj--
):
#include <iostream>
using namespace std;
class Time
{
private:
int minute;
int second;
public:
Time () {
minute = 0;
second = 0;
}
Time (int m, int s) {
minute = m;
second = s;
}
void display() {
cout << minute << " : " << second << endl;
}
// 重載前綴遞增運算符 ( ++ )
Time operator++() {
second++;
if (second >= 60) {
minute++;
second = 0;
}
return Time(minute, second);
}
// 重載后綴遞增運算符( ++ )
Time operator++(int)
{
Time t(minute, second); // 保存原始值
second++; // 對象加 1
if (second >= 60) {
minute++;
second = 0;
}
return t; // 返回舊的原始值
}
};
int main()
{
Time t1(12, 58), t2(0,45);
t1.display();
(++t1).display();
(++t1).display();
t2.display();
(t2++).display();
(t2++).display();
return 0;
}
編譯運行以上示例,輸出結果如下:
12 : 58
12 : 59
13 : 0
0 : 45
0 : 45
0 : 46
示例 6:賦值運算符重載
C++ 允許重載賦值運算符(=
),用于創(chuàng)建一個對象,比如拷貝構造函數(shù)。
下面示例重載 Rect
中的賦值運算符,并在每次拷貝的時候就把長度和寬度數(shù)值各加 1。
#include <iostream>
using namespace std;
class Rect
{
private:
double width;
double height;
public:
Rect() {
width = 0;
height = 0;
}
Rect(double a, double b) {
width = a;
height = b;
}
void display() {
cout << " width: " << width;
cout << " height: " << height;
}
void operator= (const Rect &r)
{
width = r.width + 1;
height = r.height + 1;
}
};
int main()
{
Rect r1(3.0, 4.0), r2;
r2 = r1;
cout << "r1: ";
r1.display();
cout << endl;
cout << "r2: ";
r2.display();
cout << endl;
return 0;
}
編譯和運行以上示例,輸出結果如下:
r1: width: 3 height: 4
r2: width: 4 height: 5
示例 7:函數(shù)調用運算符重載
C++ 允許重載函數(shù)調用運算符(即 ()
符號)。重載 ()
的目的不是為了創(chuàng)造一種新的調用函數(shù)的方式,而是創(chuàng)建一個可以傳遞任意個參數(shù)的運算符函數(shù)。其實就是創(chuàng)建一個可調用的對象。
下面示例將演示重載函數(shù)調用運算符的妙用:
#include <iostream>
using namespace std;
class Rect
{
private:
int width;
int height;
public:
Rect() {
width = 0;
height = 0;
}
Rect(int a ,int b) {
width = a;
height = b;
}
void operator()() {
cout << "Area of myself is:" << width * height << endl;
}
};
int main()
{
Rect r1(3, 4), r2(6, 8);
cout << "r1: ";
r1();
cout << "r2: ";
r2();
return 0;
}
編譯和運行以上示例,輸出結果如下:
r1: Area of myself is:12
r2: Area of myself is:48
示例 8:下標運算符重載
下標操作符([]
)通常用于訪問數(shù)組元素。C++ 允許重載下標運算符用于增強操作 C++ 數(shù)組的功能,重載下標運算符最重要的作用就是設置一個哨兵,防止數(shù)組訪問越界。
下面示例演示重載下標運算符:
#include <iostream>
using namespace std;
const int SIZE = 10;
class Fibo
{
private:
// 偷懶,防止把 SIZE 設置的過小
int arr[SIZE+3];
public:
Fibo() {
arr[0] = 0;
arr[1] = 1;
for(int i=2; i<SIZE; i++) {
arr[i] = arr[i-2] + arr[i-1];
}
}
int& operator[](unsigned int i) {
if (i >= SIZE) {
std::cout << "(索引超過最大值) ";
return arr[0]; // 返回第一個元素
}
return arr[i];
}
};
int main()
{
Fibo fb;
for (int i=0; i<SIZE+1; i++) {
cout << fb[i] << " ";
}
cout << endl;
return 0;
}
編譯和運行以上示例,輸出結果如下:
0 1 1 2 3 5 8 13 21 34 (索引超過最大值) 0
示例 9:類成員訪問運算符重載
C++ 允許重載類成員訪問運算符(->
),用于為一個類賦予 “指針” 行為。重載 ->
運算符時需要注意以下幾點:
- 運算符
->
必須是一個成員函數(shù); - 如果使用了
->
運算符,返回類型必須是指針或者是類的對象; - 運算符
->
通常與指針引用運算符*
結合使用,用于實現(xiàn)智能指針的功能; - 這些指針是行為與正常指針相似的對象,唯一不同的是,通過指針訪問對象時,它們會執(zhí)行其它的任務(比如,當指針銷毀時,或者當指針指向另一個對象時,會自動刪除對象)。
間接引用運算符 ->
可被定義為一個一元后綴運算符,比如:
class Ptr{
//...
X * operator->();
};
類 Ptr
的對象可用于訪問類 X
的成員,使用方式與指針的用法十分相似,如下:
void f(Ptr p )
{
p->m = 10 ; // (p.operator->())->m = 10
}
語句 p->m
被解釋為 (p.operator->())->m
。通過下面示例加深理解:
#include <iostream>
#include <vector>
using namespace std;
// 假設一個實際的類
class Obj
{
static int i, j;
public:
void f() const { cout << i++ << endl; }
void g() const { cout << j++ << endl; }
};
// 靜態(tài)成員定義
int Obj::i = 10;
int Obj::j = 12;
// 為上面的類實現(xiàn)一個容器
class ObjContainer
{
std::vector<Obj*> a;
public:
void add(Obj* obj) {
a.push_back(obj); // 調用向量的標準方法
}
friend class SmartPointer;
};
// 實現(xiàn)智能指針,用于訪問類 Obj 的成員
class SmartPointer {
ObjContainer oc;
int index;
public:
SmartPointer(ObjContainer& objc)
{
oc = objc;
index = 0;
}
// 前綴版本
// 返回值表示列表結束
bool operator++()
{
if(index >= oc.a.size())
return false;
if(oc.a[++index] == 0)
return false;
return true;
}
// 后綴版本
bool operator++(int)
{
return operator++();
}
// 重載運算符 ->
Obj* operator->() const
{
if(!oc.a[index]) {
std::cout << "Zero value";
return (Obj*)0;
}
return oc.a[index];
}
};
int main()
{
const int sz = 6;
Obj o[sz];
ObjContainer oc;
for(int i=0; i<sz; i++) {
oc.add(&o[i]);
}
SmartPointer sp(oc);
do {
sp->f();
sp->g();
} while(sp++);
return 0;
}
編譯和運行以上示例,輸出結果如下:
10
12
11
13
12
14
13
15
14
16
15
17
示例 10:邏輯非運算符重載
邏輯非(!
)運算符是一元運算符,它總是出現(xiàn)在所操作對象的左邊,如 !obj
。邏輯非運算符運算符返回的類型為 bool
類型,當對象為真值時,返回假;當對象為假值時,返回真。
下面示例演示如何重載 !
運算符:
#include <iostream>
using namespace std;
class Rect
{
private:
int width;
int height;
public:
Rect() {
width = 0;
height = 0;
}
Rect( int a, int b ) {
width = a;
height = b;
}
int area () {
return width * height;
}
// 當 width 或者 height 有一個小于 0 則返回 true
bool operator!() {
if ( width <= 0 || height <= 0 ) {
return true;
}
return false;
}
};
int main()
{
Rect r1(3, 4), r2(-3, 4);
if (!r1) cout << "r1 is not a rectangle" << endl;
else cout << "r1 is a rectangle" << endl;
if (!r2) cout << "r2 is not a rectangle" << endl;
else cout << "r2 is a rectangle" << endl;
return 0;
}
使用 g++ main.cpp && ./a.out
命令編譯和運行以上示例,輸出結果如下:
r1 is a rectangle
r2 is not a rectangle
點擊 GetIoT.tech 學習更多 C++ 編程知識!文章來源:http://www.zghlxwxcb.cn/news/detail-424544.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-424544.html
到了這里,關于十個 C++ 運算符重載示例,看完不懂打我...的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!