尝试将对象添加到向量

时间:2016-12-09 15:22:54

标签: c++ vector copy-constructor

当我尝试将对象添加到类型为vector的向量时,我不断收到C2280错误。以下是给我错误的文件

'interfaceText::interfaceText(const interfaceText &)': attempting to reference a deleted function"

interfaceText.h

#include<SFML/Graphics.hpp>
#include<vector>
#include<iostream>
#include<math.h>
#include<sstream>
#include<ctime>
#include<cstdlib>
class interfaceText{
    private:
        std::string createString();
        std::ostringstream stringStream;
        sf::Text text;
        sf::Vector2f position;
        sf::Font font;
        sf::Color color;
        //DEBUG
        int currentAngle = 1;
        sf::Color generateRandomColors();

    public:
        sf::Text returnRenderObject();
        interfaceText(sf::Vector2f textPosition, sf::Color textColor);
        void updateText(float currentangle);//std::string string, sf::Vector2f   textPosition,  sf::Color textColor);
};
extern std::vector<interfaceText>  textArray;

interfaceText.cpp

#include "interfaceText.h"

interfaceText::interfaceText(sf::Vector2f textPosition, sf::Color textColor):position(textPosition),color(textColor){

    font.loadFromFile("AvenirNextLTPro-Cn.otf");
    text.setString(createString());
    text.setPosition(position);
    text.setFont(font);
    text.setColor(color);
    textArray.push_back(*this); //<-Code that causes error?
}


std::string interfaceText::createString() {
    std::string TESTSTRING="DEBUG";
    return TESTSTRING;
}

void interfaceText::updateText(float currentAngle){//std::string string,     sf::Vector2f textPosition, sf::Color textColor) {
    text.setString(createString());
    position.x = (cos(currentAngle*3.14 / 180)* position.x/2);
    position.y = (sin(currentAngle*3.14 / 180)* position.y/ 2);
    text.setPosition(position);
    text.setColor(generateRandomColors());
    //std::cout << text.getPosition().x<<" " << text.getPosition().y <<'\n';
    currentAngle+=1;
}

sf::Text interfaceText::returnRenderObject() {
    return text;
}
sf::Color interfaceText::generateRandomColors() {
    srand(time(NULL));
    sf::Color newColor (rand()%255, rand() % 255, rand() % 255,255);
    return newColor;
}

在main.cpp中(这不是全部,因为我删除了我认为无关的代码)

#include"interfaceText.h"
#include<vector>
int main(){
    interfaceText newText(sf::Vector2f(100, 100), sf::Color(255, 255, 255, 255));
    return 0;
}

我确定导致此错误的代码(或至少触发编译器提供错误消息)

textArray.push_back(*this);
在interfaceText.cpp文件中

还有一些错误消息给出的注释如下所示:

 note: compiler has generated 'interfaceText::interfaceText' here

 see reference to function template instantiation 'void std::allocator<_Ty>::construct<_Objty,interfaceText&>(_Objty *,interfaceText &)' being compiled

从我收集的说明中,编译器正在尝试为interfaceText类添加新的ctor,但我不知道为什么

1 个答案:

答案 0 :(得分:1)

执行textArray.push_back(*this);时,您可以复制该对象。很遗憾,您无法复制interfaceText,因为它包含std::ostringstreamstd::ostringstream不可复制,因此任何将其包含为成员的类都将默认生成的复制构造函数标记为已删除。

您需要创建自己的复制构造函数并在其中构造std::ostringstream,或者您可以将实例移动到向量中,因为流是可移动的。