提问人:alex 提问时间:5/18/2022 更新时间:5/18/2022 访问量:46
如何在不使代码效率低下的情况下尊重 c++ 中的封装原则?
How to respect encapsulation principles in c++ without making the code unefficient?
问:
我是 C++ 编程的新手,我正在用 C++ 开发一个项目。 我对所有 OOP 原则(如封装和继承)都很陌生,因此我对如何在特定结构中正确设计代码表示怀疑。 例如,假设我必须定义一个这样的结构:
class c1;
class c2;
class MyCl{
public:
MyCl();
// many access methods...
//...
//...
private:
std::string _title;
int _version;
std::vector<c1> _vec;
// other private members
}
class c1{
public:
c1();
// many access methods
private:
std::vector<c2> _vec;
// other private members
}
class c2{
public:
c2();
//many access methods
private:
std::vector<std::string> _vec_str;
// other private members
}
现在假设我们有一个 MyCl 对象,我们想修改向量_vec_str中所有字符串中的单个字符串,该字符串位于结构体 (c2) 中暴露最少的部分。 那么,在这种情况下,修改该字符串的最佳选择是什么?返回 const& 似乎效率低下,因为为了修改单个字符串,我们必须复制所有结构两次(一次用于 getter,一次用于 setter)和每个子类。另一方面,返回 & 或指针更有效,因为它允许直接访问所有结构,但它不尊重封装原则。
答: 暂无答案
评论
MyCl
c1
c2
MyCl
c1
c2
struct Point{ T x, T y };
class Rectangle