C++ 中 const 重载有什么用?

2022-01-23 00:00:00 function overloading constants c++

在 C++ 中,函数的签名部分取决于它是否为 const.这意味着一个类可以有两个具有相同签名的成员函数,除了一个是 const 而另一个不是.如果你有一个这样的类,那么编译器将根据你调用它的对象来决定调用哪个函数:如果它是类的 const 实例,将调用函数的 const 版本;如果对象不是 const,则将调用另一个版本.

In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it on: if it's a const instance of the class, the const version of the function will be called; if the object isn't const, the other version will be called.

您希望在什么情况下使用此功能?

In what circumstances might you want to take advantage of this feature?

推荐答案

这只有在成员函数返回一个指针或引用你的类的数据成员(或成员的成员,或成员成员的成员,...等).通常不赞成返回非常量指针或对数据成员的引用,但有时它是合理的,或者只是非常方便(例如 [] 运算符).在这种情况下,您需要提供一个 const 和一个非常量版本的 getter.这样,是否可以修改对象的决定取决于使用它的函数,该函数可以选择将其声明为 const 或 non-const.

This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply very convenient (e.g. [] operator). In such cases, you provide a const and a non-const versions of the getter. This way the decision on whether or not the object can be modified rests with the function using it, which has a choice of declaring it const or non-const.

相关文章