[英]Function taking both pointer to member-function and pointer to const member-function
[英]How does member-function understand that the object is obtained by dereferencing a const pointer?
我创建了一个const指针,指向动态分配的abject实例。我无法理解对象本身是不是const。
首先,我试图通过使用指针调用非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或非const,但表达式也有类型。 (*p)
的类型是const A
,你不能调用const类型的非const方法。
(1)和(2)之间没有区别。 (1)是(2)的语法糖。 您应该将print方法定义为const,以便为const对象调用它。
void print() const { ... }
正如已经指出的那样,表达式有类型,(* p)的类型是const A.你不能在const类型的对象上调用非const函数,但可以调用const成员函数。 成员函数可以有一个const限定符,它将标记它们以便能够在const对象上调用或指向const对象的指针。
void print() const
{
std::cout<<a<<std::endl;
}
这将使您的代码编译。 看起来这就是你打算做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.