const char* name’ previously declared

huangapple go评论64阅读模式
英文:

const char* name’ previously declared

问题

class MyString : public string {
public:
    MyString() : string() {}
    MyString(const char* name) : string(name) {}
    MyString(const MyString& a) : string(a) {}
    MyString(const string& a) : string(a) {}
    MyString operator()(int start, int end) {
        MyString ret(substr(start, end));
        return ret;
    }
};

当我写这段代码时,显示如下错误信息:

‘const char* name’ previously declared here
   10 |             MyString(const char* name){
      |                      ~~~~~~~~~~~~^~~~
and  string(name);
      |

我该怎么办?

就像上面写的那样。

英文:
class MyString:public string
{
    public:
            MyString(){ string();}
            MyString(const char* name){
                string(name);
            }
            MyString(const MyString& a){
                    *this = a;
            }
            MyString(const string& a):string(a){}
            MyString operator()(int start,int end){
                MyString ret(substr(start,end));
                return ret;
            }
};

when I write this, it shows that

‘const char* name’ previously declared here
   10 |             MyString(const char* name){
      |                      ~~~~~~~~~~~~^~~~
and  string(name);
      |                       

what should I do?

just like words written above

答案1

得分: 2

如果你真的想编写自己的基于标准字符串类的字符串类,那么正确的方法是使用组合而不是继承。基于上面的代码,可以像这样编写:

class MyString
{
public:
    MyString() {}
    MyString(const char* name) : my_string(name) {}
    MyString(const std::string& name) : my_string(name) {}
    MyString operator()(int start, int end) const {
        return my_string.substr(start, end);
    }
private:
    std::string my_string;
};
英文:

If you really want to write your own string class based in the standard string class then the way to do it is to use composition not inheritance. Based on the code written above, something like this

class MyString
{
public:
    MyString() {}
    MyString(const char* name) : my_string(name) {}
    MyString(const std::string& name) : my_string(name) {}
    MyString operator()(int start, int end) const {
        return my_string.substr(start, end);
    }
private:
    std::string my_string;
};

huangapple
  • 本文由 发表于 2023年2月6日 17:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定