Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 控制通过C+中的成员函数更改成员变量的能力+;班_C++_Class_Constants - Fatal编程技术网

C++ 控制通过C+中的成员函数更改成员变量的能力+;班

C++ 控制通过C+中的成员函数更改成员变量的能力+;班,c++,class,constants,C++,Class,Constants,考虑 class foo { int a; int b; public: void f1(); void f2(); void f3(); }; > C++中允许支持 >在 f2()> > f3-()/ > const f1()>代码>,同时保持 b>代码>到处可变?p> 编辑:上面的示例是问题的说明,但我正在寻找是否有写入访问控制的通用解决方案是的,可以使用常量成员函数和可变属性: #include <iostream> class foo { i

考虑

class foo
{
 int a;
 int b;
public:
  void f1();
  void f2();
  void f3();
};
<> > C++中允许支持<代码> <代码> >在<代码> f2()> <代码> > <代码> f3-()/<代码> > <代码> const <代码> <代码> f1()>代码>,同时保持<代码> b>代码>到处可变?p>
编辑:上面的示例是问题的说明,但我正在寻找是否有写入访问控制的通用解决方案

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

#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();
}
#包括
福班
{
INTA;
可变int-b;
公众:
foo(){
a=10;
b=20;
}
void f1()常量{

//std::我想不用说,你不想得到无意义的答案吗?生成
f1
a
const
成员函数并声明
b
mutable
?在
f1
开头通过
auto-const&a=this->a;
?为什么阅读声明的人会关心such实现详细信息与成员函数的契约毫无关系?是否希望将实现详细信息包含在类定义中?这不是一个好主意。这是(编辑:was)问题恰恰相反。提问者希望
b
到处都是可变的,而
a
f3
f2
中是可变的,但不是
f1
…即使如此,原则仍然是一样的,这清楚地回答了问题。
不是
(这个答案)@super这是真的(我的意思并不是说答案根本上是错的),但答案也可以根据问题进行编辑。@StoryTeller那么OP可能会改进这个问题。这个答案完全回答了当前的问题。