最近,我一直想要定义一个std :: string的子类spstring。它在spstr.h声明:什么是继承std :: string的权利?
#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'继承,尤其是public [(参见相关的SO post)]被认为是一个坏主意(http://stackoverflow.com/questions/6006860/why-should-one-not -derive-从-C-STD-字符串类)。私有继承*可能被认为是足够安全的,尽管它仍然在你的类和'std :: string'之间建立了紧密的耦合。看到一个有趣的讨论[在这里滥用继承](http://www.gotw.ca/publications/mill06.htm)。至于错误,请张贴一个简短的,自包含的例子来重现问题。 – juanchopanza
你不是从std :: string(或map,vector,或任何其他容器)派生的。在我遇到这种情况的所有情况下,都有几种更好的解决方案。 无论何时您需要从stl容器派生,都应考虑封装,意思是将容器用作类的成员,或者使用私有继承。 – Peter