【问题标题】:How cast C++ class to intrinsic type如何将 C++ 类转换为内在类型
【发布时间】:2011-05-27 01:47:47
【问题描述】:

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 ];
}    

感谢您的帮助。

【问题讨论】:

  • 对于奖励积分,我如何确保“s = 5;”有效吗?

标签: c++ casting intrinsics


【解决方案1】:
class sType
{
public:
    operator int() const { return val; }

private:
    int val;
};

【讨论】:

  • 私人的好主意,但你让他无法设置它
  • @Rup:我假设 OP 知道构造函数是什么 :)
  • 顺便说一句,C++0x 允许将转换函数 (operator int()) 标记为“显式”,因此需要转换 (int)s。就目前而言,您可以只写array[s],但有时不允许这样做是不可取的,原因与有时您希望显式标记单参数构造函数相同。
  • @Steve:很高兴知道。由于隐式语义,我通常尽量避免使用转换函数。
【解决方案2】:
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 时使用该构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2014-10-09
    • 1970-01-01
    相关资源
    最近更新 更多