除了班级之外的每个人都不变,有这样的事情吗?

Constant for everyone but the class, is there such a thing?

本文关键字:每个人      更新时间:2023-10-16

我一直想知道有没有办法在不使用只能由其类修改的 getter 的情况下拥有一个类成员?

我想的是这样的。

class A 
{
    public:
        crazyconst int x;
        void doStuff()
        {
             // Gettin' stuff done
             x = someValue; // OK
        }
};
int main(int argc, char** argv)
{
     A a;
     a.x = 4; // ERROR
}

因此,它是可见的,但对其类旁边的每个人都是只读的。

您的类可以具有对私有的非const数据成员的公共const引用。

编辑:但是,我应该指出,这样做会阻止您使用编译器生成的复制构造函数和复制赋值运算符。

答案是否定的,如果没有某种getter,你就无法做到这一点。 但是,您可以使 getter 可重用,并且可以使字段的简单语法(大部分)有效,没有括号。

(C++11 必填)

template<typename Friend, typename FieldType>
class crazyconst
{
    FieldType value;
    friend Friend;
    FieldType& operator=(const FieldType& newValue) { return value = newValue; }
public:
    operator FieldType(void) const { return value; }
    FieldType operator()(void) const { return value; }
};
class A
{
public:
    crazyconst<A, int> x;
    void doStuff()
    {
        // Gettin' stuff done
        x = 5; // OK
    }
};
int main(int argc, char** argv)
{
    A a;
    int b = a.x;
    int c = a.x(); // also works
}

C++03版本:http://ideone.com/8T1Po

请注意,这将编译但不能按预期工作:

const int& the_x = a.x;
a.doStuff();
std::cout << the_x;

OTOH,这应该没问题:

const auto& ref_x = a.x;
a.doStuff();
std::cout << ref_x;