如何尊重C++没有使代码不高效?
我是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论