为某些函数设置类的一些私有成员为const

make some private members of a class const for some functions

本文关键字:成员 const 函数 设置      更新时间:2023-10-16

我有一个名为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。由于方法位于同一个文件中,因此记住这一点应该不会太难。

如果你真的需要单独封装AB,甚至在一个类中,然后为它们使用一个自己的类,并将方法移动到类中,例如:

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;
};

我相信你可以用模板进一步推广这种方法(你能提供一个函数作为模板参数吗?如果是的话,你可以让这个类完全通用)

相关文章: