当在构造函数初始化列表中初始化引用抽象类型时,如何对{}初始化与()初始化进行区分?请看下面的Bar类:
class AbstractBase
{
public:
AbstractBase() {}
virtual ~AbstractBase() = default;
virtual void ab() = 0;
};
class Foo : public AbstractBase
{
public:
Foo() {}
void ab() {}
};
class Bar
{
public:
Bar(const AbstractBase& base) : myBase{base} {}
private:
const AbstractBase& myBase;
};
int main()
{
Foo f{};
Bar b{f};
}
编译时出现错误
test5.cpp: In constructor ‘Bar::Bar(const AbstractBase&)’:
test5.cpp:22:48: error: cannot allocate an object of abstract type ‘AbstractBase’
Bar(const AbstractBase& base) : myBase{base}
^
test5.cpp:2:7: note: because the following virtual functions are pure within ‘AbstractBase’:
class AbstractBase
^
test5.cpp:8:18: note: virtual void AbstractBase::ab()
virtual void ab() = 0;
更改该行
Bar(const AbstractBase& base) : myBase(base) {}
编译和运行都很好。
阅读Stroustrup的C++11书籍时,我认为在大多数情况下,{}与()是相同的,除了存在std::initializer_list<>构造函数和其他构造函数之间存在歧义以及使用auto作为类型的情况,但这里我都不涉及。
{}
,而对于其他构造函数,则使用()
进行显式调用。 - Mooing DuckS() {}
就连编译都过不了我的代码示例! - M.M