C++ std::runtime\u错误中的显式构造函数
根据cplusplus.com,这是std::runtime_error类的实现:C++ std::runtime\u错误中的显式构造函数,c++,constructor,explicit,C++,Constructor,Explicit,根据cplusplus.com,这是std::runtime_error类的实现: class runtime_error : public exception { public: explicit runtime_error (const string& what_arg); }; 由于构造函数是显式的,我希望它只接受std::string对象 throw std::runtime_error("error message"); 不过,这段代码是编译的(GCC)。编译器不应该抱怨隐式常量c
class runtime_error : public exception {
public:
explicit runtime_error (const string& what_arg);
};
由于构造函数是显式的,我希望它只接受std::string对象
throw std::runtime_error("error message");
不过,这段代码是编译的(GCC)。编译器不应该抱怨隐式常量char*到常量字符串的转换吗?这不是显式的意思。也许用一个例子来说明这一点最简单:
struct Foo
{
explicit Foo(const std::string& s) {}
};
void bar(const Foo&) {}
int main()
{
Foo f("hello"); // OK: explicit construction from std::string
Foo f2 = std::string("hello"); // ERROR
std::string s;
bar(s); // ERROR
}
这里,
explicit
转换构造函数意味着不能从std::string
隐式构造Foo
。但是您仍然可以从const char*
构造std::string
,这在这里不是显式的意思。也许用一个例子来说明这一点最简单:
struct Foo
{
explicit Foo(const std::string& s) {}
};
void bar(const Foo&) {}
int main()
{
Foo f("hello"); // OK: explicit construction from std::string
Foo f2 = std::string("hello"); // ERROR
std::string s;
bar(s); // ERROR
}
这里,
explicit
转换构造函数意味着不能从std::string
隐式构造Foo
。但是您仍然可以从const char*
构造std::string
,而explicit
并不是这样工作的。它防止std::string
隐式转换为std::runtime\u错误,而不是const char*
转换为std::string
。这取决于std::string
的构造函数。这不是explicit
的工作方式。它防止std::string
隐式转换为std::runtime\u错误,而不是const char*
转换为std::string
。这取决于std::string
的构造函数。请注意bar(“hello”)
是错误的,不是因为Foo()
是显式的。这是因为它需要两个(链式)转换,这是不允许的(string literal->std::string->Foo)
@Nawaz很好!我将删除该选项以避免混淆问题。请注意,bar(“hello”)
是错误的,而不是因为Foo()
是显式的。这是因为它需要两个(链式)转换,这是不允许的(string literal->std::string->Foo)
@Nawaz很好!我将删除该选项,以避免混淆问题。