const数据成员

1 c++ constructor const

所以我有一个具有const字符串数据成员的类.

从用户收到的字符串本身.

如何编写可以使用它的构造函数以及如何从用户获取字符串并将其放入类中?

谢谢

And*_*owl 5

要初始化const成员(以及引用成员),您需要使用构造函数初始化列表.

这是你在C++ 11中的方法(字符串按值传递然后移动,这样当在构造函数的输入中给出rvalue时不会执行复制):

#include <string>

struct X
{
    X(std::string s_) : s(std::move(s_)) { }
//                    ^^^^^^^^^^^^^^^^^^
    std::string const s;
};
Run Code Online (Sandbox Code Playgroud)

在C++ 03中你会这样做:

#include <string>

struct X
{
    X(std::string const& s_) : s(s_) { }
//                           ^^^^^^^
    std::string const s;
};
Run Code Online (Sandbox Code Playgroud)