尝试将对象添加到向量时,获取错误C2280

Getting error C2280 when trying to add an object to a vector

本文关键字:获取 取错误 C2280 向量 对象 添加      更新时间:2023-10-16

当我尝试将对象添加到类型类的向量时,我会继续遇到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,但我不知道为什么

执行textArray.push_back(*this);时,您会制作对象的副本。不幸的是,您无法复制interfaceText,因为它包含std::ostringstreamstd::ostringstream不可复制,因此将其包含在成员中的任何类都具有标记为已删除的默认生成的复制构造函数。

您要么需要制作自己的复制构造函数并在那里构造std::ostringstream,要么可以将实例移至向量,因为流是可移动的。