7

基本 C++ 类问题:

我目前有简单的代码,看起来像这样:

typedef int sType;
int array[100];

int test(sType s)
{
  return array[ (int)s ];
}

我想要的是将“sType”转换为一个类,这样就不需要更改“return array[(int)s]”行。例如(伪代码)

class sType
{
  public:
    int castInt()
    {
      return val;
    }
    int val;
}


int array[100];    
int test(sType s)
{
  return array[ (int)s ];
}    

谢谢你的帮助。

4

2 回答 2

10
class sType
{
public:
    operator int() const { return val; }

private:
    int val;
};
于 2010-12-17T11:10:59.277 回答
5
class sType
{
  public:
    operator int() const
    {
      return val;
    }
    int val;
};

要使 s = 5 起作用,请提供一个采用 int 的构造函数:

class sType
{
  public:

    sType (int n ) : val( n ) {
    }

    operator int() const
    {
      return val;
    }
    int val;
};

然后,编译器将在需要将 sType 转换为 int 时使用该构造函数。

于 2010-12-17T11:10:38.520 回答