c++裡面也可使用陣列運算操作符:
例如:
1 #include 2 #include 34using
namespace
std;56
intmain()717
}1819 cout << n <2021
return0;
22 }
但是不是我們定義 了乙個類後,就可以使用陣列訪問操作符了呢?
被忽略的事實:
-陣列訪問符是c/c++的內建操作符;
-陣列訪問符的原生意義:陣列訪問和指標運算。
例如:a[n] <->*(a+n) <->*(n+a) <-> n[a]
指標與陣列的複習.cpp:
1 #include 2 #include 34using
namespace
std;56
intmain()7;
910for(int i=0; i<5; i++)
1114
15for(int i=0; i<5; i++)
1619
20 cout <2122
for(int i=0; i<5; i++)
2326
27for(int i=0; i<5; i++)
2831
32return0;
33 }
過載陣列訪問操作符:
-陣列訪問操作符(【】)
-只能通過類的成員函式過載
-過載函式能且僅能使用乙個引數
-可以定義不同引數的多個過載函式。
例項二(非常有意義):
1 #include 2 #include 34using
namespace
std;56
class
test714
15int& operator (const
string&s)
1621
else
if( s == "
2nd")22
25else
if( s == "
3rd")26
29else
if( s == "
4th")30
33else
if( s == "
5th")34
3738
return a[0
];39}40
41int
length()
4245
};46
47int
main()
4855
56for(int i=0; i)
5760
61 cout << t["
5th"] <62 cout << t["
4th"] <63 cout << t["
3rd"] <64 cout << t["
2nd"] <65 cout << t["
1st"] <6667
return0;
68 }
小結:string類最大程度的相容了c字串的用法。
陣列訪問符的過載能夠使得物件模擬陣列的行為
只能通過類的成員函式過載陣列訪問符
過載函式能且僅能使用乙個引數。
陣列操作符的過載
string類物件還具備c方式字串的靈活性嘛?還能直接訪問單個字元嘛?string s alb2c3d4e int n 0 for int i 0 i length i 這樣子從語法的角度是合法的 陣列訪問符時c c 中的內建操作符 陣列訪問符的原生意義是陣列訪問和指標運算 i a 等價與 a i ...
操作符過載
ifndef vertex h define vertex h class vertex vertex float px float py float pz vertex operator const vertex p vertex operator const vertex p void oper...
操作符過載
1.操作符是靜態方法,返回值表示操作結果,引數是運算元。2.操作符過載需要在過載的操作符前加上operator關鍵字。3.最好少用操作符過載,只有在意義明晰而且與內建類的操作一致時才適合使用,以免造成混亂。以建立的分數類 fraction 中的 為例,該分數類中有兩個int型的私有屬性 分子 num...