将类隐式转换为int的正确方法是什么?

时间:2014-11-17 20:15:33

标签: c++

以下类应该用作普通数组或std :: vector的索引。它基本上有助于从C接口访问数组的地址计算。

class Index
{
    public:
        int data;

        inline void manipulate(Argument arg){
           // do some manipulation on data
        }

};

为了使用如下语句,实现自动转换的正确方法是什么:

Index myIndex;
...
a[myIndex] = A(...)
f(myIndex); // f is defined as f(int idx){...}

附带问题:这个类是否会使用一个int的存储?

2 个答案:

答案 0 :(得分:3)

您可以定义隐式转换运算符:

class Index
{
    int data;
public:
    // ...
    operator int() const { return data; }    
};

侧面回答:可能。

答案 1 :(得分:0)

选择害虫和霍乱:

// Explicit Constructor
struct FirstIndex
{
    int data;
    explicit FirstIndex(const int& data)
    :   data(data)
    {}

    operator const int& () const { return data; }
    operator int& () { return data; }
};
bool operator == (const FirstIndex& a, const FirstIndex& b) { return a.data == b.data; }

// Explicit Conversion
struct SecondIndex
{
    int data;
    SecondIndex(const int& data)
    :   data(data)
    {}

    explicit operator const int& () const { return data; }
    explicit operator int& () { return data; }
};
bool operator == (const SecondIndex& a, const SecondIndex& b) { return a.data == b.data; }

// Nothing Explicit
struct ThirdIndex
{
    int data;
    ThirdIndex(const int& data)
    :   data(data)
    {}

    operator const int& () const { return data; }
    operator int& () { return data; }
};
bool operator == (const ThirdIndex& a, const ThirdIndex& b) { return a.data == b.data; }

int main()
{
    FirstIndex first(0);
    int first_result = 0;
    first += 1;
    // no match for ‘operator=’
    // first = first + 1;
    first_result = first;
    first_result == first;

    SecondIndex second(0);
    int second_result = 0;
    // error: no match for ‘operator+=’
    // second += 1;
    // no match for ‘operator+’
    // second = second + 1;
    // cannot convert ‘SecondIndex’ to ‘int’
    // second_result = second;
    second_result == second;

    ThirdIndex third(0);
    int third_result = 0;
    third += 1;
    third = third + 1;
    third_result = third;
    // This one is significant
    // error: ambiguous overload for ‘operator==’
    // third_result == third;
}