const版本何时被调用? [英] When is the const version called?
本文介绍了const版本何时被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为A类制作了 T运算符[](int i)const和 T&运算符[](int i)。
I made "T operator[](int i) const" and "T& operator[](int i)" for class A.
(还尝试过使用 const T& operator [](int i)const和 T& operator [](int i))
(and I also tried it for "const T& operator[](int i) const" and "T& operator[](int i)")
该操作符打印一个值
A a;
int k = a[0];
k = a[0];
const int l = a[0];
结果:三个非const版本的调用。
result : three calls of non-const version.
如何调用const版本?
我应该使用const class吗?
不使用const类就没有机会调用const版本的函数吗?
How can I call const version? Should I use const class? There is no chance to call a function that is const version without using const class?
推荐答案
const参考:
const A& b=a;
k=b[0];
或const转换:
k=const_cast<const A&>(a)[0];
这篇关于const版本何时被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文