运算符<的默认返回值是多少和 C++ 中的运算符[] (视觉工作室 6)?

发布于 2024-08-21 22:42:29 字数 643 浏览 5 评论 0 原文

我继承了一个大型 Visual Studio 6 C++ 项目,需要将其翻译为 VS2005。一些类定义了operator<和运算符[],但不在声明中指定返回类型。 VS6允许这样做,但VS2005不允许。

我知道 C 标准指定普通函数的默认返回类型是 int,并且我假设 VS6 可能遵循这一点,但这也适用于 C++ 运算符吗?或者 VS6 可以自己计算出返回类型吗?

例如,代码定义了一个如下所示的自定义字符串类:

class String {
  char arr[16];
  public:
    operator<(const String& other) { return something1 < something2; }
    operator[](int index) { return arr[index]; }
};

VS6 是否会简单地将两者的返回类型都设置为 int,或者它会足够聪明地计算出operator[] 应该返回 char 且operator<;应该返回一个 bool (而不是始终将两个结果都转换为 int )?

当然,我必须添加返回类型以使此代码兼容 VS2005 C++,但我想确保指定与以前相同的类型,以免立即更改程序行为(我们目前正在寻求兼容性;我们'稍后将标准化)。

I've inherited a large Visual Studio 6 C++ project that needs to be translated for VS2005. Some of the classes defined operator< and operator[], but don't specify return types in the declarations. VS6 allows this, but not VS2005.

I am aware that the C standard specifies that the default return type for normal functions is int, and I assumed VS6 might have been following that, but would this apply to C++ operators as well? Or could VS6 figure out the return type on its own?

For example, the code defines a custom string class like this:

class String {
  char arr[16];
  public:
    operator<(const String& other) { return something1 < something2; }
    operator[](int index) { return arr[index]; }
};

Would VS6 have simply put the return types for both as int, or would it have been smart enough to figure out that operator[] should return a char and operator< should return a bool (and not convert both results to int all the time)?

Of course I have to add return types to make this code VS2005 C++ compliant, but I want to make sure to specify the same type as before, as to not immediately change program behavior (we're going for compatibility at the moment; we'll standardize things later).

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

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

发布评论

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

评论(1

一页 2024-08-28 22:42:29

默认情况下,operator< 返回一个 bool

operator[] 默认返回 int (我认为),但几乎可以肯定应该将其更改为返回集合包含的任何内容。对于上面给出的字符串示例,这将是 charwchar_t

operator< returns a bool by default.

operator[] returns int by default (I think), but it should almost certainly be changed to return whatever the collection contains. For the String example you gave above, that would be a char or wchar_t.

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