考虑:
struct Foo
{
Foo(std::string str) {}
};
struct Bar
{
Bar(Foo f) {}
};
int main(int argc, char* argv[])
{
Foo f("test");
Bar b1(f);
Bar b2(std::string("test"));
Bar b3("test");
return 0;
}
这无法根据 b3 的声明进行编译(“无法将参数 1 从‘const char [5]”转换为“Foo”)。这是有道理的,因为没有直接的方法将 const char 转换为 Foo。但是,有一种方法可以将 const char 转换为 std::string,然后使用它来构造 Foo(这就是 b1 和 b2 中发生的事情),这就是我想要的,因为它使 API 更好使用(不必每次都显式实例化 Foo 或 std::string)。
所以我的问题是:有没有办法让编译器隐式调用 Foo(std::string) 复制构造函数?换句话说,有没有办法使像 b3 那样的声明起作用,让它与 b2 相同,而不用为 Foo 声明 const char* 复制构造函数? (最后一件事是显而易见的方法,但我的真实代码当然没有这么简单,我宁愿不必添加 const char* 复制构造函数并正确处理构造函数中的所有其他初始化并将其保存在与 std::string 复制构造函数同步)。
最佳答案
如果 c++11 是可接受的,您可以向 Foo
添加一个委托(delegate)构造函数,它接受一个 const char*
并只调用另一个构造函数:
struct Foo
{
Foo(std::string str) {}
Foo(const char* str) : Foo(std::string(str)) {}
};
或者,您可以使用 c++14 的 std::string
literal:
using namespace::std::string_literals;
Bar b3("test"s);
您还可以通过让两个构造函数调用一个单独的函数来模拟委托(delegate)构造函数:
struct Foo
{
Foo(std::string str) { init(str); }
Foo(const char* str) { init(str); }
void init(std::string str) {}
};
上面的缺点是你需要仔细考虑你在初始化列表中所做的任何事情你现在需要在 init
的主体中做。
关于c++ - 隐式调用拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217373/