简而言之,当该类未定义复制构造函数且没有默认构造函数时,我想将元素添加到类元素的向量中。这是一个最小的例子(感谢juanchopanza修复我的例子):
class MyType {
public:
MyType(int height, int width);
MyType() = delete;
}
#include <vector>
int some_function() {
// Define the vector.
std::vector<MyType> array;
// Define an element.
MyType element(1,2);
// Now, how do I add an element to the vector?
//array.resize(1); // NO DEFAULT CONSTRUCTOR SO THIS WON'T WORK.
//array.push_back(element); // NO COPY CONSTRUCTOR SO THIS WON'T WORK.
}
我最好的猜测是,我不能在类中使用向量,除非它有复制构造函数或默认构造函数。寻找验证或启发。
答案 0 :(得分:5)
只要类型是可移动构造的,您就可以使用emplace_back
就地构建它:
array.emplace_back(1,2);
但请注意,您的示例 有一个复制构造函数,所以这也可以,与您的声明相反:
MyType element(1,2);
array.push_back(element);
以下是您的示例的简化工作版本:
struct MyType
{
MyType(int height, int width) {}
MyType() = delete;
};
#include <vector>
int main()
{
std::vector<MyType> array;
array.emplace_back(1,2);
}