const 成员函数不允许什么?
class A{
private:
int a;
public:
A() {a = 4;}
const int& random1() const {return a; }
//int& random2() const {return a; }
const int* random3() const {return &a;}
//int* random4() const {return &a;}
};
int main(){
A objA;
cout<<objA.random1()<<"\n";
cout<<*objA.random3()<<"\n";
}
如上所述,不允许使用 random2()
和 random4()
。不知何故,我一直都知道这一点,但直到今天,我在编写自己的代码时才遇到它。
除了这两种情况之外,还有哪些情况在 const 成员函数中是不允许的?
对 C++ 标准文本的任何引用也会有所帮助。谢谢!
class A{
private:
int a;
public:
A() {a = 4;}
const int& random1() const {return a; }
//int& random2() const {return a; }
const int* random3() const {return &a;}
//int* random4() const {return &a;}
};
int main(){
A objA;
cout<<objA.random1()<<"\n";
cout<<*objA.random3()<<"\n";
}
random2()
and random4()
are not permitted as defined above. I somehow knew this all along but never came across it while writing my own code, until today.
What all except these two cases is not permitted in const member functions?
Any reference to C++ standard text will also be helpful. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先要明白const T*是一个指向某些不能改变的T的指针。要记住的第二件事是所有成员实际上都是通过
this->
访问的。所以(§9.3.1):
它的作用(§9.3.2):
函数上的
const
使this
指针成为const T*
。这就是这些示例失败的原因:在
int&
变体中,a
的访问方式为this->a
,this 是
const T*
,因此a
是const int
。并且const int
不能隐式转换为int&
。与其他功能相同。换句话说,当一个函数是 const 时,它会在类中的所有内容上添加一个 const,并且您不能隐式地抛弃该 const 。
First understand that
const T*
is a pointer to someT
that cannot be changed. The second thing to remember is all members are actually accessed viathis->
.So (§9.3.1):
And what it does (§9.3.2):
A
const
on a function makes thethis
pointerconst T*
.This is why those examples fail: In the
int&
variant,a
is accessed asthis->a
,this
isconst T*
, soa
is aconst int
. Andconst int
cannot be implicitly converted toint&
. Same with the other function.In other words, when a function is
const
it smacks aconst
on everything in the class, and you can't implicitly cast theconst
away.Const 成员函数不能调用非常量成员函数,即使它们不更改任何成员数据。有时您需要提供同一函数的 const 和非 const 版本,因为 this 指针隐式传递给成员函数并在重载决策中发挥作用。
Const member functions can't call non-const member function, even if they don't change any member data. Sometimes you need to provide both const and non-const versions of the same function, because this pointer is implicitly passed to member functions and plays a role in overload resolution.