【问题标题】:Control the ability to change member variable via member function in C++ class通过 C++ 类中的成员函数控制更改成员变量的能力
【发布时间】:2018-06-19 12:25:05
【问题描述】:

考虑

class foo
{
 int a;
 int b;
public:
  void f1();
  void f2();
  void f3();
};

C++ 中是否支持允许af2()f3() 中可变,但在f1()const,同时保持b 在任何地方都可变?

编辑:上面的例子是问题的说明,但我正在寻找是否有通用的解决方案来编写访问控制

【问题讨论】:

  • 我想你不想要废话的答案是不言而喻的?
  • 使f1成为const成员函数并声明bmutable?
  • f1 的开头通过auto const &a = this->a; 遮蔽它怎么样?
  • 为什么阅读声明的人会关心与成员函数的合约无关的实现细节?
  • 您希望您的实现细节包含在类定义中吗?这不是一个好主意。

标签: c++ class constants


【解决方案1】:

是的,可以使用 const 成员函数和可变属性:

#include <iostream>
class foo
{
 int a;
 mutable int b;
public:
    foo() {
        a = 10;
        b = 20;
    }
    void f1() const{
        // std::cout << ++a << std::endl; // this won't compile
        std::cout << a << std::endl;
        std::cout << ++b << std::endl;  // This compile despite f1 being const because b is declared as mutable
    }
    void f2() {
        std::cout << ++a << std::endl;// This compile because both a and b are mutable in f2
        std::cout << ++b << std::endl;   
    }
    void f3() {
        std::cout << ++a << std::endl;// This compile because both a and b are mutable in f3
        std::cout << ++b << std::endl;   
    }
};
int main()
{
    std::cout << "Hello, world!\n";
    foo f;
    f.f1();
    f.f2();
    f.f3();
}

【讨论】:

  • 这是(编辑:是)问题的完全相反。提问者希望 b 处处可变,af3f2 中可变,但不是 f1
  • ...即便如此,原理还是一样的,这清楚地回答了这个问题。
  • not这个答案)
  • @super 确实如此(我并不是要暗示答案从根本上是错误的),但最好对答案进行编辑以适应问题。
  • @StoryTeller 那么OP应该可以改进这个问题。这个答案完全回答了当前的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多