如果流试图引用一个已删除的函数

ifstream attempting reference to a deleted function

本文关键字:一个 删除 函数 引用 如果      更新时间:2023-10-16

我正在为虚拟锦标赛编写代码。问题是团队类有一个ifstream对象,我理解流对象没有复制构造函数,因此我将playing8从团队对象的向量转换为指向对象的指针,这样团队对象就不会被复制。但是现在我得到了这个错误

Error   16  error C2280: 
'std::basic_ifstream<char,std::char_traits<char>>::basic_ifstream(const std::basic_ifstream<char,std::char_traits<char>> &)' : 
    attempting to reference a deleted function
c:program files (x86)microsoft visual studio 12.0vcincludexmemory0 592 1   Assignment3

如何解决这个问题而不从团队类中删除ifstream对象?下面是tournament.h

的代码
#include "team.h"
class Tournament
{
    std::ofstream out_file;
    std::ifstream in_file;
    std::vector<team> teams;
    std::vector<team*> playing8;
    public:
    void schedule();
    void schedule2();
    void tfinal();
    void selectPlaying8();
    void rankTeams();
    void match(int,int);
    Tournament();
    ~Tournament();
};

锦标赛构造函数代码:

Tournament::Tournament()
{
    srand(time(NULL));
    in_file.open("team_list.txt");
    string input;
    int noteam=0;
    while (getline(in_file, input)){
        noteam++;
    }
    in_file.close();
    for (int i = 0; i < noteam;i++){
        string x=to_string(i)+".csv";
        team temp(x);
        temp.set_teamform((6 + rand() % 5) / 10.0);
        teams.push_back(temp);
    }
}

选择播放8的代码:

void Tournament::selectPlaying8(){
    for (int i = 0; i < 7; i++) {
        playing8.push_back(&teams[i]);
        playing8[i]->set_playing();
    }
}

团队类属性

#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "Player.h"
class team 
{
private:
    std::ifstream in_file;
    std::vector<Player> playing11;
    std::string teamname;
    std::vector<Player> player;
    bool playing;
    float matchperformance;
    float teamform;
    float team_rank_score;
};

我用的是visual studio express 2013

此代码

playing8.push_back(&teams[i]);

使用编译器生成的复制构造函数生成team类实例的副本。它只是简单地复制每个成员。

ifstream没有提供复制构造函数(它被删除了),因此你会得到这个错误。

要解决这个问题,你需要使用ifstream*指针,或ifstream&引用。

不是每个变量都必须是类变量。一般来说,变量应该保存在尽可能小的范围内。

保持你的文件作为本地变量,没有必要把它们作为类字段