构造函数不适用于继承自std :: string的类 [英] Constructor doesn't work for class inherited from std::string

查看:149
本文介绍了构造函数不适用于继承自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)

这篇关于构造函数不适用于继承自std :: string的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆