C++:类的只读和只写版本的语义

标签 c++ inheritance encapsulation

在我的程序中,我有一个名为Foo 的数据结构。程序的一部分从一组参数构造 Foo,因此需要访问可变方法。该程序的另一部分将仅从 Foo 中读取,因此不应访问可变方法。

完成此任务的最佳方法是什么,或者我对类应该如何工作的看法是错误的?我过去用过这种方式:

class FooR {
public:
    int read() { return x; }
protected:
    int x;
};

class FooRW : public FooR {
    void mutate(int nx) { x = nx; }
};

但这种方式感觉就像是在滥用继承,而且我认为在程序的两个部分中使用两个名称非常相似的类可能会造成混淆。有更好的方法吗?你能以一些巧妙的方式使用 const 吗?

编辑: @jens 指出在程序的只读部分使用 const 引用应该可行,这让我意识到了解我的数据结构实际上是一棵树很重要,类似于:

class Foo {
public:
    void splitNode();
    Foo *getChild(int n) const; // const Foo?
private:
    Foo *children[2];
};

有没有办法强制 const Foo 只返回对其子项的 const 引用?

最佳答案

程序中不需要改变对象的部分应该只使用 const 引用,并将非可变成员函数标记为 const。

class FooR {
public:
    int read() const { return x; }
    void mutate(int nx) { x = nx; }
private:
    int x;
};

void f1(FooR const& obj)
{
    int x = obj.read();
    // cannot use obj.mutate(x+1);
}
void mutatingFunction(FooR&);

您可以在工厂或建筑物中进行构建,并返回 std::unique_ptr<FooR const>std::shared_ptr<FooR const>以防止其他人使用可变接口(interface)。

相同的方法适用于树。声明一个常量重载返回 Foo const* ,以及返回非常量指针的非常量重载。后者不能从 const 引用中使用。

class Foo {
public:
    void splitNode();
    Foo const* getChild(int n) const;
    Foo* getChild(int n); 
private:
    Foo *children[2];
};

关于C++:类的只读和只写版本的语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32157621/

相关文章:

c++ - 为什么 Google 在成员变量之后命名访问器和修改器?

c - 为指向函数的指针编写一个 getter

c++ - OnShow 事件上的 ProcessMessages c++ builder

c++ - 如何编写 "pointer to const"类型特征?

css - css 样式继承是如何工作的

Laravel - 扩展模型

python - 继承中命名空间的顺序是什么?

c# - Unity封装,属性强制我重写变量名?

c++ - 将 QString 转换为 char* 不稳定?

C++ Winapi - MPEG 电影作为动画背景