【发布时间】:2021-09-06 14:15:51
【问题描述】:
我知道在 C++ 中扩展内置类已被弃用,但出于某些原因我仍然想这样做。
我想将我的自定义方法添加到从 std::string 类扩展/继承的类 (str)(这是一个示例)
但是当我这样做时,我会遇到一些问题,例如 std::string 类中已经存在的方法(内置方法),
#include <bits/stdc++.h>
using namespace std;
class str : public string {
public:
string s;
str(string s1) {
s = s1; //ig the problem is here
}
};
int main() {
str s("hello world");
cout << s.size(); //prints out 0 not 11 => length of "hello world"
}
我该如何解决这个问题?
【问题讨论】:
-
您正在混合组合和继承。选一个。对于继承,你应该去掉
string s;成员。 -
@Yksisarvinen 你能解释一下继承吗?
-
请注意,很少有标准类被设计为公开继承,因为它们没有
virtual析构函数。这意味着你不能多态地使用它们。 -
私有继承与组合基本相同,所以就用组合吧。如果您觉得需要从标准容器继承,那么您应该将其视为您的设计存在缺陷的标志。
-
关于坏习惯,习惯(好和坏)往往会坚持下去。所以最好开始在任何地方都养成良好的习惯并坚持下去?