2010-09-30 153 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