【发布时间】:2013-12-29 00:53:18
【问题描述】:
最近,我一直想定义一个std::string的子类spstring。它在 spstr.h 中声明:
#include <cctype>
#include <string>
#include <algorithm>
#include <sstream>
#include <stdint.h>
#include <xstring>
class spstring : public std::string {
public:
spstring(std::string s):std::string(s){} //Declare the constructor
int stoi(); //Declare stoi
spstring Spstring(std::string s); ////Declare mandatory conversion function
};
spstring spstring::Spstring(std::string s)
{
spstring spstr(s);
return(spstr);
}
但是,在 main.cpp 中测试时:
spstring byteaddstr(std::string(argv[4])); //convertchar* to spstring
int byteadd;
byteadd=byteaddstr.stoi(); //call byteaddstr.stoi
未能遵守:
错误 C2228:“.stoi”左侧必须有类/结构/联合
听起来很奇怪,既然byteaddstr确实是spstring的一个实例,为什么不能调用它的成员函数呢?
【问题讨论】:
-
您通常不希望从 STL 容器派生。
-
一般来说,从
std::string继承被认为是个坏主意,尤其是公开(see related SO post)。私有继承可能被认为足够安全,尽管它仍然在您的类和std::string之间强加了紧密耦合。请参阅abuses of inheritance here 上的有趣讨论。至于错误,请发布一个简短的、独立的示例来重现该问题。 -
您不是从 std::string (或地图、向量或任何其他容器)派生的。在我遇到这种情况的所有情况下,都有几种更好的解决方案可用。每当您需要从 stl 容器派生时,请考虑封装,这意味着要么将容器用作类的成员,要么使用私有继承。
-
请注意,按值传递 std::string 效率低下,请改用 const 引用或移动语法。
-
关于使用 STL 容器定义新类型,组合是比继承最好的方法。见这里:stackoverflow.com/questions/14089088/…
标签: c++ string class inheritance