类中的 ofstream - 尝试引用已删除的函数

Ope*_*L97 6 c++ string parameters fstream char

我在类中有一个成员变量,其类型是ofstream和一个包含字符串参数的构造函数:

class dogs
{
public:
    ofstream dogsFile;

    dogs(string location)
    {

    }
};
Run Code Online (Sandbox Code Playgroud)

出现以下错误:

错误 2 错误 C2280: 'std::basic_ofstream>::basic_ofstream(const std::basic_ofstream> &)' : 尝试引用已删除的函数 c:\users\pc\documents\visual studio 2013\projects\database\database\数据库.cpp 26 1 数据库

我再次尝试了这段代码,但我没有使用字符串,而是使用了 char*:

class dogs
{
public:
    ofstream dogsFile;

    dogs(char* location)
    {

    }
};
Run Code Online (Sandbox Code Playgroud)

错误消失了。为什么?为什么字符串会出错?

编辑:这是整个代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


class dogs
{ 
    ofstream dogsFile;

public:
    dogs(string location)
    {

    }
};

int main(int argc, _TCHAR* argv[])
{
    dogs dog = dogs("dog.bin");
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_* Po 4

Dieter 的原始答案似乎是正确的。即这将编译:

dogs *dog = new dogs("dog.bin");
Run Code Online (Sandbox Code Playgroud)

你的行不会,请参阅他关于复制构造函数的答案。

dogs(“dog.bin”) 将创建一个对象,然后“=”将复制它并将其交给狗。无法复制其中包含 ofstream 的对象。

您还可以使用以下方法修复此问题

dogs dog("dog.bin");
Run Code Online (Sandbox Code Playgroud)

反而。