make 方法不更改自己的类变量而不使它们常量
Making method not change its own class variables without making them constant
>假设一个类中有变量,并且该类的方法不应在不使变量恒定的情况下更改成员变量。如果可能的话,如何实现?
是的。 const
-限定成员函数:
struct X {
int a;
void f() const {
// a = 42; // illegal
}
};
使用常量方法。例如:
class Foo {
public:
// this won't be able to change any member variable
void bar() const;
}
void Foo::bar() const {
}
相关文章:
- 没有为自己的结构调用列表推回方法
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- C++从对象自己的类中删除对象
- QDial:如何将 int 值传递给需要常量字符*的 Qfile?
- 使用 std::optional,而不是自己的结构
- 子轴围绕父轴而不是他自己的轴旋转
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 将字符串数组传递给接受常量字符**的函数
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- 重载 + 自己的类和 std::string 的运算符
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 如何访问模板参数自己的模板参数?
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 将矩阵乘以我自己的输入的向量
- make 方法不更改自己的类变量而不使它们常量
- 将一个常量cstring附加到我自己的String类对象
- 类成员有自己的常量成员,因此构造函数被隐式删除