在这样的声明中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表示在该函数中任何变量的值都不能改变
class Test{
private:
int a;
public:
void test()const{
a = 10;
}
};
像这个例子一样,如果你试图改变测试函数中变量的值,你会得到一个错误。
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方法中修改,而不违反const约定。
如果您希望对象记住某个特定方法被调用的次数,同时不影响该方法的“逻辑”常量,则可能需要使用这个(例如)。
当您在方法签名中使用const时(如您所说的:constchar*foo()const;)你告诉编译器,这个方法(这里是foo)不能改变它指向的内存。
我想补充一点。
也可以将其设置为常量和常量&&
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
}
请随意改进答案。我不是专家