【问题标题】:How does member-function understand that the object is obtained by dereferencing a const pointer?成员函数如何理解对象是通过取消引用 const 指针获得的?
【发布时间】:2019-10-21 01:00:44
【问题描述】:

我创建了一个指向动态分配的 abject 实例的 const 指针。我无法理解对象本身是否为 const。

首先我尝试使用指针调用一个非常量成员函数,不出所料,它导致了编译错误,因为(这是我的解释,不知道是不是真的)这个由成员函数创建的指针分配给该 const 指针。它没有产生任何东西。

其次,我尝试取消引用指针并调用该非常量成员函数。我认为现在由成员函数创建的this指针不会是const指针,因为编译无法知道p(即*p)返回的对象是否由const指针返回。原来我错了。

成员函数如何理解?

#include<iostream>

class A
{
    int a=4;
public:
    A()
    {}

 void   print()
    {
        std::cout<<a<<std::endl;
    }
};


int main()
{
    const A* p = new A();  

   p->print(); //1 causes compile error
   (*p).print(); //2 causes compile error


  return 0;
}

我认为标记为 2 的行不会产生编译错误。 它会导致编译错误。错误消息是:

"a.cpp: In function ‘int main()’:
a.cpp:21:13: error: passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]
    p->print(); //1 causes compile error
             ^
a.cpp:10:9: note:   in call to ‘void A::print()’
  void   print()
         ^~~~~
a.cpp:22:15: error: passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]
    (*p).print(); //2 causes compile error
               ^
a.cpp:10:9: note:   in call to ‘void A::print()’
  void   print()
         ^~~~~

【问题讨论】:

  • 我不明白你在困惑什么。如果一个取消引用const A*,则剩下一个const A,不是吗?
  • 然后 const A* p = new A();和 const A* p = new const A();没区别吧?
  • 为什么创建的对象类型转换为 const ?我的意思是我创建一个非常量整数和指向该整数的 const 整数。
  • 因为您在将其分配给const A* 类型的变量时就这样做了。 C++ 允许您将非 const 对象隐式转换为 const 类型,因为这样做是完全安全的。
  • @Sneftel 谢谢,现在我明白了:)

标签: c++ class pointers constants


【解决方案1】:

如前所述,表达式有类型,(*p) 的类型是 const A。不能在 const 类型的对象上调用非 const 函数,但可以调用 const 成员函数。成员函数可以有一个 const 限定符,它将标记它们能够在 const 对象或指向 const 对象的指针上调用。

void print() const
{
   std::cout<<a<<std::endl;
}

这将使您的代码编译。看起来这就是你打算做的事情。

【讨论】:

    【解决方案2】:

    (1)和(2)之间没有区别。 (1) 是 (2) 的语法糖。 您应该将 print 方法定义为 const 以便为 const 对象调用它。

    void print() const { ... }
    

    【讨论】:

      【解决方案3】:

      变量有类型,因此可以是 const 或非常量,但表达式也有类型。 (*p)的类型是const A,不能调用const类型的非常量方法。

      【讨论】:

      • 嗯,你说 new 创建的对象是 const ?为什么因为我可以将一个 const integer 指针指向一个 non-const integer 。有原因吗? ----我得到了答案----
      猜你喜欢
      • 2019-11-09
      • 2012-02-10
      • 1970-01-01
      • 2013-04-21
      • 2016-08-17
      • 2021-06-04
      • 1970-01-01
      • 2016-08-13
      相关资源
      最近更新 更多