ifstream 尝试引用已删除的函数

3

我正在为一个虚拟锦标赛编写代码。问题是团队类有一个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.0\vc\include\xmemory0 592 1   Assignment3
我该如何解决这个问题,而不需要从team类中删除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。
2个回答

4
这段代码。
playing8.push_back(&teams[i]);

使用编译器生成的复制构造函数复制被推回的 team 类实例。它试图简单地复制每个成员。

ifstream 没有提供复制构造函数(已删除),因此会出现此错误。

要解决此问题,您需要使用 ifstream* 指针或 ifstream& 引用。


那么我该如何在不调用复制构造函数的情况下向playing8添加地址? - Maaz Jamal
@MaazJamal “不调用复制构造函数?”这是错误的问题。我告诉过你,你需要修复这些ifstream oftream字段。实际上,我相信你根本不需要它们,可以使用引用从类外部传递它们。 - πάντα ῥεῖ

2

并非所有的变量都需要成为类变量。一般来说,变量应该尽可能地保持在最小的范围内。

将您的文件作为本地变量存储,没有必要将它们作为类字段。


这是我会做的。存储文件名,并使用本地变量来处理流。 - Mats Petersson
我最初是这样做的,但认为它会导致错误。感谢您的提示。 - Maaz Jamal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接