2013-02-26 76 views
1

有人可以請解釋以下語法差異如何改變運營商的工作方式?運營商超負荷語法澄清

T & operator()(type one, type two) 
const T * operator()(type one, type two) 
T & operator()(type one) const 
const T & operator()(type one) const 
+0

有用的鏈接:http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B – 2013-02-26 08:36:01

回答

5

假設他們都是成員,他們都是按價值獲得type對象。這意味着,至少在語義上,身體操作員擁有自己的type對象副本。 operator()語法表示實例可調用。在operator()之後,例如(type a, type b),是參數列表。

這一個需要兩個type s type,並返回對T的引用。不能在const實例上使用。

T & operator()(type one, type two) 

它可以被稱爲是這樣的:

MyFunctor x; 
type a, b; 
T& r = x(a,b); // take reference 
T c = x(a,b); // make copy from reference. Assumes T has copy constructor 

這個版本有兩個type S,並返回一個指針const T。不能在const實例上使用。可以調用T的非const方法。

const T * operator()(type one, type two) 

實施例:

MyFunctor x; 
type a, b; 
const T* p1 = x(a,b); // pointer to const 
T* p2 = x(a,b);  // Error! Must have const T* on LHS 

這一個接受一個type,並且返回到T的參考。可以用於所有實例,常量或非常量。根據什麼返回的引用是指,它可能打破允許你通過一個const方法修改內部數據const一致性:

T & operator()(type one) const 

最後一部作品爲一個以上,但沒有非const方法的任何返回指的是可以調用的。

const T & operator()(type one) const 

MyFunctor x; 
type a; 
const T& r = x(a); // take reference to const 
T c = x(a);  // make copy from reference. Assumes T has copy constructor 
T& r = x(a);  // Error! Cannot take reference to non-const! 
+0

你能澄清的最後兩個之間的區別是什麼?我很困惑const在一切之後做什麼。另外,在最後一個例子中,我們如何聲明T c = x(a)?爲什麼它不一定是const T c = x(a)? – 2013-02-27 22:33:37

+0

@AshleyPinkman const表示它是一個'const'成員函數,即它不能修改實例的數據或調用任何非const成員函數。你被允許做這個'T c = x(a)',因爲你正在複製*。 – juanchopanza 2013-02-27 22:36:40