gpt4 book ai didi

c++ - this 和成员函数的常量正确性

转载 作者:行者123 更新时间:2023-11-30 00:52:02 25 4
gpt4 key购买 nike

假设我有一个通用类 A

class A {
...
int a; // a member
void foo() const{...} // a member function qualified as const
...
};

这意味着如果我声明一个 A 的实例,比如 A k; 然后我调用 k.foo(); this 指针在对 foo 的调用上/内部起作用,是 const A * const 类型的东西。

现在我想知道为什么这个blog post中的代码有效,尤其是关于为什么这不适用于全局变量。

我的解释是关于指针别名的隐藏操作,比如 this 指针被隐式复制,在复制过程中结果不再是 const(出于某种原因。 .. ) 但它仍然是一个 this 指针,意思是指向同一实例的指针。

我的问题是:如果 const 在成员函数的接口(interface)声明之后应用,它到底做了什么?对于链接的博文,您有具体的答案吗?


代码来自博客

#include <iostream>

class counter {
public:
int i;
counter();
int inspect() const;
void increment();
};

counter sigma_inspect; // sigma_inspect is global

counter::counter() { i = 0; }

int counter::inspect() const {
sigma_inspect.increment();
return i;
}

void counter::increment() {
++i;
return;
}

int main(void) {
counter a;
std::cout << a.inspect() << "\n";
std::cout << sigma_inspect.inspect() << "\n";
std::cout << sigma_inspect.inspect() << "\n";
return 0;
}

最佳答案

博文中的调用使用的是 sigma_inspect,它是非常量,它正在调用非常量方法,而不是通过 const this 调用所述方法> 指针。所以呢?作者似乎期望魔术而不是他所写的显而易见的东西。就像拥有

T* t = ...;
const T* ct = t;
t->foo(); // foo() is not const, but hey,
// I also have a const pointer now (ct),
// so why can I still use this???

通常,如果有人说 C++ 愚蠢,它会告诉你更多关于作者而不是语言的信息:)

关于c++ - this 和成员函数的常量正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com