继承std :: string的方法是什么?

时间:2013-12-11 06:58:18

标签: c++ string class inheritance

最近,我一直想要定义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”的左边必须有class / struct / union

听起来很奇怪,因为byteaddstr确实是spstring的一个实例,为什么不能调用它的成员函数呢?

2 个答案:

答案 0 :(得分:5)

在C ++中,可以解析为函数声明的任何声明,例如......

    spstring byteaddstr(std::string(argv[4])); //convertchar* to spstring

解析为函数声明。

即。不是变量。

在这种特殊情况下,一个解决方案是添加额外的括号:

    spstring byteaddstr(( std::string(argv[4]) )); //convertchar* to spstring

这在C ++中被称为最令人烦恼的解析,尽管有些人不同意Scott Meyers对该术语的原始用法是否适用于现在使用的一般情况。


顺便说一句,人们应该有一个很好的理由std::string派生,因为它增加了复杂性和混乱(你可以放心地忽略对动态分配的担忧,因为代码动态分配std::string值得任何东西。所以,我建议你不这样做。

答案 1 :(得分:0)

继承std::string(以及STL容器)是一个坏主意。它们不是作为基类运行的。

重要的是,它们不一定具有虚拟析构函数,因此可以使派生类难以进行内存管理。

你也会失去可读性:如果我看到一个STL类或函数,那么我确切地知道会发生什么,因为它假设我已经记住了标准。使用派生类,我必须依赖其文档或程序注释。

所以我的回答:没有正确的方法从std :: string 继承。