英文:
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;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论