operator int() 是類型轉換運算符,比如:
struct A { int a; A(int i):a(i){} operator int() const { return a; } }; void main() { A aa(1); int i = int(aa); int j = aa; //作用一樣 }
該函數的返回值類型就是函數名,所以不用顯式地表示出。
什麼叫返回類型就是函數名?
============================
返回類型是int,函數名也是int,就是說不寫成 int operator int() const { return value; },
返回類型被省去了。operator
int()
is a conversion
operator, which allows this class to be used in place of an int
.
If an object of this type is used in a place where an int
(or
other numerical type) is expected, then this code will be used to get a value of the correct type.
For example:
int i(1);
INT I(2); // Initialised with constructor; I.a == 2
i = I; // I is converted to an int using `operator int()`, returning 2.