Vector无法正确创建对象

Hug*_*iro 4 c++ stdvector

我创建了一个带有一些静态数据的类.像这样的东西:

class Object
{
public:
    Object();
    Object( Point center, double area );
    Object( int cx, int cy, double area );
    ~Object();
    //and other public stuffs here...
private:
    Point center;
    double area;
    static double totalArea;
    static int objCounter;
    static double areaMean;
};
Run Code Online (Sandbox Code Playgroud)

而不是在我的构造函数和析构函数中:

Object::Object()
{
    this->setCenter( Point() );
    this->setArea( 0.0 );
    objCounter++;
    totalArea += 0;
    areaMean = totalArea / objCounter;
}
/*this is just the default constructor I 
have two others that increment real area, not 0*/ 

Object::~Object()
{
    //cout << "Destructor called!\n"; //put it just to test
    objCounter--;
    totalArea -= this->area;
    areaMean = totalArea / objCounter;
}
Run Code Online (Sandbox Code Playgroud)

所以我的目的是知道创建了多少个对象,它是总面积和平均面积.我用简单的语句测试了它,例如:

Object first;
Object second;
cout << Object::getObjCounter() << "\n"; 
///I have the get method implement origanally
Run Code Online (Sandbox Code Playgroud)

一切都没问题.对象类正确计算instaces的数量.我使用简单数组测试:

Object test[ 10 ];
cout << Object::getObjCounter() << "\n";
Run Code Online (Sandbox Code Playgroud)

太棒了......它的确有效; 我测试了动态分配:

Object *test = new Object[ 10 ];
cout << Object::getObjCounter() << "\n";
delete [] test;
Run Code Online (Sandbox Code Playgroud)

再次......它有效.但当我尝试:

vector< Object > test( 10, Object() );
cout << Object::getObjCounter() << "\n";
Run Code Online (Sandbox Code Playgroud)

它在stdout中给我零...我在构造函数和析构函数中放置标志以查看它为什么会发生.它告诉我,当我使用所显示的向量语句时,构造函数被调用,而不是按顺序调用析构函数!为什么????对我没有意义!有人可以向我解释一下吗?另外,任何人都可以帮助我使用vector来实现与简单数组相同的效果,这意味着:在一些内容中有一堆对象,并正确计算它?问题是我需要矢量功能,如删除和添加元素,以及调整大小,但我不想重新发明轮子.提前致谢.

小智 10

您需要为Object类定义一个复制构造函数.http://www.cplusplus.com/articles/y8hv0pDG/