为某些函数设置类的一些私有成员为const
make some private members of a class const for some functions
我有一个名为myClass
的类:
myClass
{
int myFunction1();
int myFunction2();
private:
int A;
int B;
};
在myFunction1
中A不应该改变,但B可以改变。在myFunction2
中,B不应改变,但A可以改变。
是否有办法使灵活的const
为每个功能?如const B
为function1,反之亦然
这并不容易做到。你可以声明一个方法const
,它将所有变量都变成const
。可以声明成员mutable
,这样即使在const
函数中也可以对其进行变异。但是,您不能仅将成员mutable
声明给某些方法。
但问题是:你为什么要那样?简单地说,不要在方法中修改A
。由于方法位于同一个文件中,因此记住这一点应该不会太难。
如果你真的需要单独封装A
和B
,甚至在一个类中,然后为它们使用一个自己的类,并将方法移动到类中,例如:
class MyClass {
private:
AContainer A;
BContainer B;
public:
void myFunction1(){ B.myFynction1(A.get()); }
void myFunction2(){ A.myFunction2(B.get()); }
class BContainer {
int B;
public:
int get(){ return B;}
myFunction1(int A); // May only change B, A is provided as parameter
}
class AContainer {
int A;
public:
int get(){ return A;}
myFunction2(int B); // May only change A, B is provided as parameter
}
}
如果您真的需要实现这种行为,您可以将您的int
s包装成类,这些类将在提供get/set访问的同时成为特定函数的朋友,就像这样(非常简化,缺少所有必要的实用程序-只是为了说明这一点):
class TIntA{
public:
TIntA(int _i) : m_data(_i) {}
// this function will be able to modify the m_data member but other
// functions will have to use the get()
friend int myClass::myFunction1();
int get() const {return m_data;}
private:
int m_data;
};
我相信你可以用模板进一步推广这种方法(你能提供一个函数作为模板参数吗?如果是的话,你可以让这个类完全通用)
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- 如何在声明为 const 的方法中更改类成员
- 如何定义一个没有重复代码的继承的 const 类成员函数?
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 在类 (C++) 之外设置 const int 成员变量
- 不允许运算符 const 参数调用 const 成员函数
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 有人可以用"显式运算符 const GUID_t&() const"来解释成员函数的函数吗?
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- 在 C++ 中通过引用传递类成员时,Const 不起作用
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- 静态数据成员:它"const declaration / constexpr definition"起作用?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 声明与 const 变量和成员函数相同的标识符
- 有效地初始化 const std::vector 类成员
- 为什么我可以调用一个从const方法更改成员的方法
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 在类声明中初始化 const 成员变量时在调试模式下出现异常