我非常熟悉C/C++标准函数的声明。最近我看到了类似这样的内容:
int myfunction(char parameter) const
上面只是一个假设性的例子,我甚至不知道它是否有意义。我指的是参数之后的部分。常量。这是什么?
更真实的例子:
wxGridCellCoordsArray GetSelectedCells() const
这可以在这里找到。 那么该行末尾的
const
文本究竟是做什么的?const关键字表示函数不会改变任何数据成员,除非它们被标记为mutable。
只有成员函数可以被标记为const,这意味着在函数内部不会更改任何成员。
在函数后面出现的const关键字可以保证函数调用者不会更改任何成员数据变量。它还会改变函数签名,这是一些C++程序员不太了解的事情。实际上,您可以通过在具有相同名称的函数后添加const关键字来重载C++中的函数。例如:
void changeValue() const;
void changeValue();
以上两个函数都是有效的,且彼此重载。我经常看到一些C++ API和框架使用这种重载来避免用户在const和非const函数中调用这些函数时出现大量编译错误。这是否是良好的C++软件工程尚有争议。我想这是不好的实践,但了解它会改变函数签名是很好的。
例如,给定以下类:
// In header
class Node {
public:
Node();
void changeValue() const;
~Node();
private:
int value;
};
// in .cpp
void Node::changeValue() const {
this->value = 3; // This will error out because it is modifying member variables
}
// In header
class Node {
public:
Node();
void changeValue() const;
~Node();
private:
mutable int value;
};
// in .cpp
void Node::changeValue() const {
this->value = 3; // This will not error out because value is mutable
}
mutable
的一个例子是当您的对象具有“上次访问时间”时间戳变量时。即使有人使用const
方法访问对象,您也希望能够更新该变量。 - jxh const
修饰函数参数,表示该函数不应修改该参数,添加 const
会导致编译器防止您无意中这样做。同样,如果您编写不应更改类的任何成员变量的成员函数,则可以像那样将整个函数声明为 const
,从而防止您这样做。 const
告诉用户:“此函数不修改此参数”。向成员函数添加 const
告诉用户:“此函数不修改类的任何成员”(除了显式的可变成员)。const
关键字在方法后面表示隐式的 this
参数(它被设置为调用该方法的对象的地址)指向一个常量对象。class Foo {
int x;
mutable int y;
public:
void bar () {
Foo *me = this; // * this is an implicit parameter
// that points to the instance used
// to call bar()
assert(&x == &this->x); // * accesses to class members are
// implicitly taken from this
x = 1; // * can modify data members
}
void bar () const {
// Foo *me = this; // * error, since "bar() const" means
// this is a "const Foo *"
const Foo *me = this; // * ok
// x = 1; // * error, cannot modify non-mutable
// members of a "const Foo"
y = 0; // * ok, since y is mutable
}
};
在C语言中,类似的功能是通过访问指向struct Foo *
和const struct Foo *
的函数实现的:
struct Foo {
int x;
int y;
};
void Foo_bar (Foo *this) { /* ... */ } /* can modify this->x and this->y */
void cFoo_bar (const Foo *this) { /* ... */ } /* cannot modify this->x nor this->y */
mutable
的 analong。
GetSelectedCells
函数没有可以更改的参数吗? - itsols