1

假设我有一个包含几个数据成员的类,我想要一个返回一个数据成员的类方法,下一次调用它时返回另一个数据成员的值。就像是:

class MyClass
{
    public:
        MyClass():switch(0){};
        int get();
    private:
        int intA, intB;
        int sw;
};        
int MyClass::get()
{ 
    if ( (++sw)%2 )
        return intA;
    else
        return intB;
}

更优雅的方式是什么?我非常不喜欢 if...else 语句。对于返回之类的东西很好,但如果我实际上使用更复杂的操作,我最终会复制大量代码。或者必须在解决我指向的元素后调用的每个方法中创建第二个方法。

理想情况下,我更愿意做的是使用某种形式的指针,所以我可以做

class MyClass
{
    public:
        MyClass():switch(&intA){};
        int get();
        void toggleSwitch();
    private:
        int intA, intB;
        int * sw;
};        
int MyClass::get()
{
    return *sw;
}
void MyClass::toggleSwitch()
{
    if ( sw == &intA )
        sw = &intB;
    else
        sw = &intA;
}

或者类似的东西。我可以调用 toggleSwitch(),让我的类轻松地对一个值或另一个值进行操作。

不过我还是不喜欢。我宁愿尽可能避免使用 if's,在这种情况下我不应该需要一个。裸指针的这种使用应该是相当安全的,但我想我可以有类似 std::unique_ptr 的东西来保存每个元素,然后 std::swap 它们。但随后指针将拥有元素,而它们将成为动态内存。

那么有没有更好的方法呢?

4

2 回答 2

3

嗯,switch是一个关键字,但我会顺其自然。指针数组怎么样?

int *fields[] = {&intA, &intB};

int MyClass::get()
{
    return *fields[++switch % 2];
}

如果您以后可以有其他变量,这将很好地扩展。

或者可能:

int MyClass::get()
{
    return *fields[switch = 1 - switch];
}

如果你返回一个引用,那么你可以在内部使用 get() 。

int &MyClass::get()
{
    return *fields[switch = 1 - switch];
}
于 2012-12-20T03:49:48.480 回答
0

我将封装一个切换值的概念:

template<typename T>
class Toggleable {
    T first;
    T second;
    T* current;
    T* other;

public:
    Toggleable(const T& first, const T& second)
    : first(first),
      second(second),
      current(&first),
      other(&second) {
    }

    bool toggle() {
        std::swap(current, other);
    }

    const T& get() const {
        return *current;
    }
}

然后用作:

class MyClass
{
    Toggleable<int> value;

    public:
        MyClass()
        : value(42, 1729)
        {
        }

        const int& get() {
            value.toggle();
            return value.get();
        }
};    
于 2012-12-20T09:52:20.063 回答