c++ - C++ 中 this* 的类型

标签 c++ pointers const-pointer

这听起来可能很愚蠢。在 C++prime 第 5 版 P258 中,它说:

by default, the type of this is a const pointer to the nonconst version of the class type.for example,by default, the type of this in a Sales_data member function is Sales_data *const.

我可以理解,因为 this* 是一个 const 指针,这意味着它指向的对象一旦初始化就不能改变。但是它说:

although this is implicit, it follows the normal initialization rules,which means that(by default)we cannot bind this to a const object.

但我写了下面的代码,它仍然编译得很好:

class Test{
public:
    Test() = default;
    Test(const string &s): teststr(" ") {};
    Test(int a) : testint(a) {};
    Test(const string &s, int a): teststr(s), testint(a) {};
    string getstr() const { return teststr; };
    int getint() { return testint; };   //there is no const here
private:
    string teststr;
    int testint = 0;
};

int main(){
    Test a("abc",2);

    cout << a.getint() << " ";
    cout << a.getstr() << endl;
    cout << endl;

    return 0;
}

所以我的问题是: 如果编译器可以很好地编译它是否有'const',那为什么重要? 然后书上说:

after all,the body of isbn doesn't change the object to which this points, so our function would be more flexible if this were a pointer to const.

我想知道灵 active 是什么?你能给我一些例子吗?

最佳答案

对于初学者来说,this 通常被描述为一个常量指针。

然而,this实际上是一个指针类型的prvalue(纯右值)。您不能将任何内容分配给基本类型的纯右值,这意味着 this 的“const-ness”。

this 的确切类型取决于方法的 cv 限定。一个经验法则是 cv 限定只是简单地附加到通常的指针类型之前 - 即,如果 Class 的方法被标记为 const,那么类型是 const 类*

if the compiler can compile it fine whether there is a 'const' or not,why does it matter?

如果(且仅当)this 的指针类型是const,您不能修改类的成员。

Class const* ptr; // ptr->data is also const, not modifiable through this pointer

Class* ptr; // ptr->data isn't const - can be modified.

方法上的 const 限定符允许您区分const 对象的方法和非const 对象的方法,后者通常必需品。

关于c++ - C++ 中 this* 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606364/

相关文章:

c - 使用指向 FILE 类型的 const 指针是个好主意吗?

java - 您如何在 Java 中重现常量指针的行为?

c++ - 在 C++ 中通过指针和引用传递 vector

c++ - C++可以设计一种将指针保存在连续内存中并且不会使它们无效的数据结构吗?

c++ - QDialog定位错误

c++ - C++ 中的二维 int 数组

c - 如何在指针数组中传递完整数组

c++ - 如何实现在构造函数中使用自身的对象的析构函数

c++ - 如何将模板类容器的迭代器传递给函数?