在这样的声明中const的含义是什么?这个常数使我困惑。
class foobar
{
public:
operator int () const;
const char* foo() const;
};
在这样的声明中const的含义是什么?这个常数使我困惑。
class foobar
{
public:
operator int () const;
const char* foo() const;
};
当前回答
当您在方法签名中使用const时(如您所说的:constchar*foo()const;)你告诉编译器,这个方法(这里是foo)不能改变它指向的内存。
其他回答
与函数声明一起使用的const关键字指定它是一个const成员函数,它将无法更改对象的数据成员。
const表示该方法承诺不会更改类的任何成员。即使对象本身被标记为const,也可以执行如此标记的对象成员:
const foobar fb;
fb.foo();
将是合法的。
看看C++中“const”的用法有多少?了解更多信息。
这些常量意味着如果“with const”方法更改内部数据,编译器将出错。
class A
{
public:
A():member_()
{
}
int hashGetter() const
{
state_ = 1;
return member_;
}
int goodGetter() const
{
return member_;
}
int getter() const
{
//member_ = 2; // error
return member_;
}
int badGetter()
{
return member_;
}
private:
mutable int state_;
int member_;
};
测试
int main()
{
const A a1;
a1.badGetter(); // doesn't work
a1.goodGetter(); // works
a1.hashGetter(); // works
A a2;
a2.badGetter(); // works
a2.goodGetter(); // works
a2.hashGetter(); // works
}
阅读此处了解更多信息
我想补充一点。
也可以将其设置为常量和常量&&
So,
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
}
请随意改进答案。我不是专家
当您在方法签名中使用const时(如您所说的:constchar*foo()const;)你告诉编译器,这个方法(这里是foo)不能改变它指向的内存。