为什么C+&#x2B中的const转换操作员毫无意义?

发布于 2025-01-24 19:50:50 字数 403 浏览 3 评论 0原文

在“ C ++底漆”,练习14.47中,有一个问题:

解释这两个转换之间的区别 操作员:

  struct intemal {
    操作员const int();
    操作员int()const;
}
 

我不知道为什么我在github上找到的答案说第一个const是毫无意义的,因为对于一个转换操作员不应定义返回类型,此const这是未指定的,编译器将忽略它。但是我还发现一些人说这意味着该函数将返回const值。

所以,我想知道哪一个是正确的,为什么?

In "C++ Primer", exercise 14.47, there is a question:

Explain the difference between these two conversion
operators:

struct Integral {
    operator const int();
    operator int() const;
}

I don't know why the the answer I found on GitHub says that the first const is meaningless, because for one conversion operator should not define return type, this const here is unspecified, it will be ignored by the compiler. But I also found some guys say that it means the function will return a const value.

So, I wonder which one is correct, and why?

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

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

发布评论

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

评论(1

最佳男配角 2025-01-31 19:50:50

编译器将忽略它。

这是因为 expr#6

如果prvalue最初具有类型cv t,则t是CV Unqualified的非阶级,非阵列类型,则在进行任何进一步分析之前,将表达式调整为t

这意味着在您的特定示例中,const int将在进一步之前调整为int分析由于int是内置类型而不是类型。

哪一个是对的?

即使第一个转换功能的返回类型为const int,在进行进一步分析之前,它将调整为int


而第二个转换功能上的const表示指针该函数类型const intempal*。这意味着它(转换函数)可以与const以及非const Integral对象一起使用。这是从 class.this.this

如果声明成员函数const,则其类型为const x*,...

it will be ignored by compiler.

This is because of expr#6 which states:

If a prvalue initially has the type cv T, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

This means that in your particular example, const int will be adjusted to int before further analysis since int is a built in type and not a class type.

which one is right?

Even though the return type of the first conversion function is const int, it will be adjusted to int prior to any further analysis.


While the const on the second conversion function means that the this pointer inside that function is of type const Integral*. This means that it(the conversion function) can be used with const as well as non-const Integral object. This is from class.this

If the member function is declared const, the type of this is const X*, ...

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