构造函数不适用于继承自std :: string的类

构造函数不适用于继承自std :: string的类

问题描述:

#include <string>

class MyString : public std::string 
{
 public:    
   MyString() {}
};

但是下面的用法:

MyString s = "Happy day";
MyString s("Happy Day");
MyString s = (MyString)"Happy day";

它们都不工作。

似乎有一些与构造函数/运算符声明/ overridding有关,但任何人都可以帮助指出我在哪里可以找到这些资源?

It seems that there's something to do with constructors/operators declaration/overridding, but can anyone help point out where may I find these resources?

谢谢。

你需要为你想要转换成字符串的不同类型定义一些构造函数。这些构造函数基本上只是将参数传递到底层的 std :: string

You need to define some constructors for the different types that you want to be able to convert into your strings. These constructors can basically just hand the parameters through to the underlying std::string.

手动创建它们,编译器为您创建一个默认和复制构造函数:

If you don't manually create them, the compiler creates a default- and a copy-constructor for you:

MyString() : std::string() { }
MyString(const MyString &other) : std::string(other) { }

要允许从字符串字面量构造,需要一个构造函数,它接受 const char *

To allow construction from string literals, you need a constructor that takes a const char*:

MyString(const char* other) : std::string(other) { }


b $ b

使用 const std :: string& 的构造函数也可用于转换 std :: string s到你的字符串类型。如果你想避免正常字符串的隐式转换,你应该使它显式

A constructor that takes a const std::string& would also be useful to convert std::strings to your string type. If you want to avoid implicit conversions of normal strings, you should make it explicit:

explicit MyString(const std::string &other) : std::string(other) { }

(由于我的原始版本已填满错误,我无法删除接受的答案,因此已编辑)

(Edited because my original version was full of errors and I can't delete the accepted answer)