Ala*_*ing 2 c++ inheritance constructor stl vector
如果我创建派生类的大小2 std::vector
,则只调用一次构造函数.如果我创建基类的大小为2的向量,则构造函数被调用两次.
我通常不会发布复制问题的完整代码,但在这种情况下,它可以很短:
#include <iostream>
#include <vector>
class Base {
public:
Base() { std::cout << "base constructor" << std::endl; }
virtual ~Base() {}
};
class Derived : public Base {
public:
Derived() { std::cout << "derived constructor" << std::endl; }
};
int main() {
std::vector<Base> base(2);
std::cout << "----------------" << std::endl;
std::vector<Derived> derived(2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的输出对我来说是:
base constructor
----------------
base constructor
derived constructor
Run Code Online (Sandbox Code Playgroud)
为什么输出不是以下内容:
base constructor
base constructor
----------------
derived constructor
derived constructor
Run Code Online (Sandbox Code Playgroud)
我在Linux上使用gcc 4.5.2.
你在欺骗自己:派生对象的一个默认构造调用两个构造函数.
现在,您没有看到的是复制构造函数,实际上在两种情况下都会调用两次.
的构造函数vector
,你打电话让一个其值类型的默认构造,然后拷贝到这一点每一个元素:
//std::vector<Derived> v(2);
std::vector<Derived> v(2, Derived()); // same thing!
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
715 次 |
最近记录: |