【问题标题】:ifstream attempting reference to a deleted functionifstream 尝试引用已删除的函数
【发布时间】:2015-05-31 07:57:09
【问题描述】:

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

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

如何在不从团队类中删除 ifstream 对象的情况下解决此问题? 这是锦标赛的代码。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。

【问题讨论】:

    标签: c++ c++11 ifstream


    【解决方案1】:

    这段代码

    playing8.push_back(&teams[i]);
    

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

    ifstream 没有提供复制构造函数(它已被删除),因此您会收到此错误。

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

    【讨论】:

    • 那么我应该如何在不调用复制构造函数的情况下将地址添加到play8?
    • @MaazJamal "没有调用复制构造函数?"这是个错误的问题。我告诉过你,你需要修复这些 ifstream oftream 字段。实际上我相信你根本不需要它们,使用参考从你的课堂之外传递它们。
    【解决方案2】:

    并非每个变量是类变量。一般来说,变量应该保持在尽可能小的范围内。

    将您的文件保存为本地变量,无需将它们作为类字段。

    【讨论】:

    • 这是我会做的。存储文件名,并为流使用局部变量。
    • 这就是我最初所做的,但认为它会导致错误。感谢您的提示。
    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2020-05-02
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多