我正在看一本根据标准 C++11 教授 C++ 的书。该书展示了一个将子类标记为 explicit
的示例。
据我所知,这将使编译器检查与动态绑定(bind)有关的错误,并且您还必须在覆盖虚函数时显式使用 override
关键字,否则它不会工作。我确实设置了一个小程序来测试这个,但我得到了一个错误。而且我从未见过关键字 explicit
的示例在其他任何地方都像那样使用过。
这本书是否提供了不准确的信息,或者我只是错过了什么?我是否应该单独使用 override
关键字?
class base {
public:
virtual void f() {
cout << "Called from base" << endl;
}
};
class derived explicit : public base {
public:
void f() override {
cout << "Called from derived" << endl;
}
};
在终端中写入 c++ -std=c++11 main.cpp -o main.exe
给我以下错误:
error: expected unqualified-id
class derived explicit : public base {
^
最佳答案
以这种方式使用 explicit
在任何标准中都不是有效的 C++。来自 explicit
上的 cppreference :
1) Specifies that a constructor or conversion function (since C++11) is explicit, that is, it cannot be used for implicit conversions and copy-initialization.
2) [...] (C++20 specific...)
...最重要的是:
The explicit specifier may only appear within the decl-specifier-seq of the declaration of a constructor or conversion function (since C++11) within its class definition.
这不包括您在书中展示的案例。看看 curated list of books并考虑改用其中之一。
关于c++ - 书籍示例在类声明中使用 "explicit"关键字。无效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090339/