【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
像这样的声明中const
的含义是什么? const
使我感到困惑。
class foobar
{
public:
operator int () const;
const char* foo() const;
};
#1楼
当您使用const
方法签名(像你说: const char* foo() const;
)你告诉编译器内存指向this
不能用这种方法来改变(这是foo
这里)。
#2楼
C ++常识中 Const成员函数的含义 :基本中级编程给出了明确的解释:
X类的非常量成员函数中的this指针的类型为X * const。 也就是说,它是指向非常量X的常量指针(请参见常量指针和指向常量的指针[7,21])。 因为此对象所指向的对象不是const,所以可以对其进行修改。 在类X的const成员函数中,此类型为const X * const。 也就是说,它是指向常量X的常量指针。由于此对象所指向的对象是const,因此无法对其进行修改。 这就是const和非const成员函数之间的区别。
因此,在您的代码中:
class foobar
{
public:
operator int () const;
const char* foo() const;
};
您可以这样认为:
class foobar
{
public:
operator int (const foobar * const this) const;
const char* foo(const foobar * const this) const;
};
#3楼
我想补充以下几点。
您也可以将 其const &
和const &&
所以,
struct s{
void val1() const {
// *this is const here. Hence this function cannot modify any member of *this
}
void val2() const & {
// *this is const& here
}
void val3() const && {
// The object calling this function should be const rvalue only.
}
void val4() && {
// The object calling this function should be rvalue reference only.
}
};
int main(){
s a;
a.val1(); //okay
a.val2(); //okay
// a.val3() not okay, a is not rvalue will be okay if called like
std::move(a).val3(); // okay, move makes it a rvalue
}
随时改善答案。 我不是专家
#4楼
与函数声明一起使用的const关键字指定它是const成员函数 ,它将无法更改对象的数据成员。
#5楼
const表示该方法保证不会更改该类的任何成员。 即使对象本身被标记为const
,您也可以执行标记为该对象的成员:
const foobar fb;
fb.foo();
是合法的。
请参见C ++中“ const”的用途是什么? 欲获得更多信息。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3146761