要初始化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)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |