不能将类构造函数中新创建的对象复制到C++中的向量成员

不能将类构造函数中新创建的对象复制到C++中的向量成员,c++,class,vector,scope,copy,C++,Class,Vector,Scope,Copy,在类构造函数中,我初始化其他对象并将这些对象推送到我的类向量成员。据我所知,向量创建对象的一个副本并存储它,这样它就不会超出范围。但是,在验证另一个类函数中的对象时,它们不再初始化。下面是一个示例代码来解释该行为: #include <iostream> #include <string> #include <vector> #include <algorithm> class Square { private: int size

在类构造函数中,我初始化其他对象并将这些对象推送到我的类向量成员。据我所知,向量创建对象的一个副本并存储它,这样它就不会超出范围。但是,在验证另一个类函数中的对象时,它们不再初始化。下面是一个示例代码来解释该行为:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Square {
    private:
    int size_ = 0;
    int colour_ = 0;

    public:
    Square(){
        size_ = 0;
        colour_ = 0;
    }
    void init(int size, int colour) {
        size_ = size;
        colour_ = colour;
    }
    int get_size() { return size_; }
};


class SetSquares {
    private:
    std::vector<Square> squares_;
    int number_;

    public:
    SetSquares(): number_(0) {}
    void init(int num) {
        number_ = num;
        squares_.clear();
        squares_.resize(num);
        for (int i=0; i < num; i++) {
            Square square;
            square.init(i, i);
            squares_.push_back(square);
        }
    }

    void sample(int i) {
        if (i >= number_) { return; }
        std::cout << "Square size is: " << squares_[i].get_size() <<       std::endl;
    }
};

int main()
{
    SetSquares set_of_squares;
    set_of_squares.init(7);
    set_of_squares.sample(4);
    return 0;
}

resizen将在向量中创建n个默认构造元素,push_back将在这些n个元素之后追加新元素。按照注释中的建议,使用保留和推回或调整大小和索引运算符。

而不是正方形。推回正方形做正方形[i]=square;正如Tomek在下面提到的,调整尺寸线是一个问题。拆下那根线并保持向后推也起作用。谢谢