2010-09-30 155 views
3

有一類這樣的:運營商[]重載

class X { 
    public: 
     ... 
    private: 
     int changeable[3]; 
     int unchangeable[3]; 
};  

這是其理想的用法:

X x; 
x[0] = 1; // here changeable[0] should be used 
a = x[0]; // here unchangeable[0] should be used 

是否有限定class Xoperator[]以實施的方法嗎?

+0

您可以實現第一種情況下,可以實現第二種情況但不能兩者一起 – Gaim 2010-09-30 21:24:01

+0

他可以重載運營商,它可能會選擇基於上下文。 – JSchlather 2010-09-30 21:26:58

回答

3

我可能會用一個代理對象解決這個問題:所以,現在當你調用

class Xproxy 
{ 
    int& changeable; 
    int& unchangeable; 

    Xproxy(int& c, int& u) : changeable(c), unchangeable(u) 
    {} 

    Xproxy& operator=(int i) 
    { 
    changeable=i 
    return *this 
    } 

    operator int() 
    { 
    return unchangeable; 
    } 
}; 


class X 
{ 
    int changeable[3]; 
    int unchangeable[3]; 

    Xproxy operator[](int i) 
    { 
    return Xproxy(changeable[i], unchangeable[i]) 
    } 
}; 

操作上的[] X,你有裏面兩個可變和不可變的字段引用的對象Xproxy 。

如果您嘗試分配給Xproxy對象,它將調用操作符=,該操作符指定給可更改對象的引用。如果您嘗試將Xproxy對象分配給int,則會調用從不可更改字段中拉出的cast操作符。

2

排序,但你需要鬼鬼祟祟。

class X { 
private: 
    class XIndex; 
public: 
    XIndex operator[](int); 
    //... 
}; 

class X::XIndex { 
public: 
    operator int() const; 
    void operator=(int val); 
private: 
    friend class X; 
    XIndex(int* lvalue, int const* rvalue); 

    int* _lval; 
    int const* _rval; 

    // Disallow copy and assignment. 
    XIndex(const XIndex&); 
    XIndex& operator=(const XIndex&); 
}; 

X::XIndex X::operator[](int i) { 
    // Check array bound? 
    return XIndex(&changeable[i], &unchangeable[i]); 
} 

// Implementation of X::XIndex methods is an exercise. 

請注意,如果x [num]表達式出現在=運算符的左邊以外的任何位置,則使用「rvalue」。如果需要,還可以添加operator+=operator*=等。

+1

哦,你知道做這一切的想法被認爲是不好的形式,對吧? – aschepler 2010-09-30 21:32:28

+0

是啊!使用它非常方便。 – 01d 2010-09-30 21:40:11

0

我想我有一個「排序」的解決方案。這不是一個確切問題的解決方案,但是,我相信,這是更實際的使用。

的想法是簡單地說,一個const X變量將導致訪問unchangeable_,一個non-const X變量會導致訪問changeable_

class X { 
    public: 
    const int & operator[](int index) const { 
     cout << __PRETTY_FUNCTION__ << " index = " << index << "\n"; 
     return unchangeable_[ index ]; 
    } 

    int & operator[](int index) { 
     cout << __PRETTY_FUNCTION__ << " index = " << index << "\n"; 
     return changeable_[ index ]; 
    } 

    private: 
    int changeable_[ 3 ]; 
    int unchangeable_[ 3 ]; 
}; 

void foo(X const & x1) { 
    int a = x1[ 1 ]; // reading from x 
} 

int main() { 
    X x; 

    x[ 0 ] = 1;   // writing to x 
    int a = x[ 1 ];  // reading from x 

    foo(x); 
} 

輸出是:

int& X::operator[](int) index = 0 
int& X::operator[](int) index = 1 
const int& X::operator[](int) const index = 1