如何投射 C++类到内在类型

发布于 2024-10-08 17:53:16 字数 426 浏览 0 评论 0原文

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

感谢您的帮助。

Basic C++ class question:

I have simple code currently that looks like something like this:

typedef int sType;
int array[100];

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

What I want, is to convert "sType" to a class, such that the "return array[ (int)s ]" line does not need to be changed. e.g. (pseudocode)

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


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

Thanks for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

¢蛋碎的人ぎ生 2024-10-15 17:53:16
class sType
{
public:
    operator int() const { return val; }

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

private:
    int val;
};
病毒体 2024-10-15 17:53:16
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 时使用该构造函数。

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

To make s = 5 work, provide a constructor that takes an int:

class sType
{
  public:

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

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

The compiler will then use that constructor whenever it need to convert an sType to an int.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文