【发布时间】:2017-02-22 17:09:00
【问题描述】:
我在派生类的复制构造函数中遇到了我不理解的行为。
class A {
A(const A&);
public:
A() = default;
};
class B : public A {
friend class Factory;
B(const int v) : A(), m_test_val(v) {}
public:
int m_test_val;
B(const B&); // no implementation, just declaration
};
class Factory {
public:
static B create(const int v) {
return B(v);
}
};
int main() {
B b = Factory::create(2);
std::cout << b.m_test_val << '\n';
return 0;
}
我不明白的行为是工作复制构造函数B::B(const B&); 的问题,但是它没有任何实现。
当我改用 B::B(const B&) = default; 时,我收到一条错误消息,指出我在 Factory::create() 函数的返回语句(A::A (const A&) 是私有的,没有故意实现)。
当然,当我使用B::B(const B&) = delete; 时,编译器会告诉我我使用了一个已删除的函数。
复制构造函数怎么可能在没有实现的情况下仅通过声明工作?
注意:示例代码基于更大的代码,其行为方式相同,希望我没有遗漏任何内容。
【问题讨论】:
标签: c++ copy-constructor