在这样的声明中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限定符意味着可以对foobar的任何值调用这些方法。当您考虑对常量对象调用非常量方法时,就会出现不同。考虑您的foobar类型是否具有以下额外的方法声明:
class foobar {
...
const char* bar();
}
方法bar()是非常量的,只能从非常量值访问。
void func1(const foobar& fb1, foobar& fb2) {
const char* v1 = fb1.bar(); // won't compile
const char* v2 = fb2.bar(); // works
}
const背后的思想是标记不会改变类内部状态的方法。这是一个强大的概念,但实际上在C++中无法实现。与其说是保证,不如说是承诺。还有一个经常破碎且容易破碎的。
foobar& fbNonConst = const_cast<foobar&>(fb1);
C++公共知识:基本中级编程中Const成员函数的含义给出了明确的解释:
类的非常量成员函数中此指针的类型X是X*常量。也就是说,它是指向非常数X的常数指针(见Const Pointers和Pointers to Const[7,21])。因为对象它所指的不是常量,可以修改。类型这在类X的常量成员函数中是常量X*const。那个是,它是指向常量X的常量指针。因为它是常量,不能修改。这就是常量和非常量成员函数之间的差异。
因此,在您的代码中:
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;
};
这里const表示在该函数中任何变量的值都不能改变
class Test{
private:
int a;
public:
void test()const{
a = 10;
}
};
像这个例子一样,如果你试图改变测试函数中变量的值,你会得到一个错误。
这些常量意味着如果“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
}
请随意改进答案。我不是专家