如何尊重C++没有使代码不高效?

发布于 2025-01-29 22:27:35 字数 812 浏览 3 评论 0原文

我是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&amp;似乎是不效率的,因为为了修改单个字符串,我们必须两次复制所有结构(一个用于getters,一个用于设置器),每个子类用于每个结构。另一方面,返回&amp;或指针更有效,因为它允许直接访问所有结构,但不尊重封装原则。

i am a noobie in c++ programming and i'm developing a project in c++.
I am new to the all the OOP principles like encapsulation and inheritance, and due to this i have a doubt on how to properly design the code in particular structures.
Suppose for example i have to define a structure like that:

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
}

Now suppose we have an object of MyCl and we want to modify a single string amongst all in the vector _vec_str, placed in the least exposed part of the structure(c2).
So in that case what is the best option to modify that string respecting the encapsulation principle? Returning const& seems unefficient, as in order to modify a single string we have to copy all the structure two times (one for the getters, and one for the setters) and for each subclass. On the other hand, returning & or pointers is more efficient as it allows a direct access to all the structure, but it doesn't respect encapsulation principles.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文