【问题标题】:C++. How to write to file from functionC++。如何从函数写入文件
【发布时间】:2014-12-20 10:19:22
【问题描述】:

我有函数必须在文件中写入一些东西。

我是这样尝试的:

int main() {
    std::ofstream fout;
    fout.open("OUTPUT.TXT");
    i = searchLexemes(input, i, 1, fout);
}

searchLexemes 是这样定义的:

int searchLexemes(std::string value, int i, int type, std::ofstream fout);

如果我像在 main() 中那样调用 searchLexemes,Visual Studio 会给我错误:

智能感知:“std::basic_ofstream<_elem _traits>::basic_ofstream(const std::basic_ofstream<_elem _traits>::_Myt &_Right) [с _Elem=char, _Traits=std::char_traits]" (объявлено в строке 1034 из "C:\Program Files\Microsoft Visual工作室 11.0\VC\include\fstream") недоступно c:\Users\Badina\Documents\Visual Studio 2012\Projects\PLT lab1\PLT lab1\Исходный код.cpp 191 33 PLT lab1

我用的是俄罗斯版的VS 2012,但我想问题一定很清楚。

【问题讨论】:

  • 参考foutstd::ofstream&amp; fout

标签: c++ visual-studio-2012 c++11


【解决方案1】:

使用reference 像这样声明您的函数:

int searchLexemes(const std::string& value, int i, int type, std::ofstream& fout);

出现此错误的原因是std::ofstream 没有公共复制构造函数(例如:ofstream(const ofstream&amp; rhs)),或者在 C++11 中明确标记为 deleted。

【讨论】:

    【解决方案2】:

    你应该调用 fout.open 函数,传入文件名。

    但如果你真的想那么,

    int searchLexemes(std::string value, int i, int type, std::ofstream *fout);
    int main() {
        std::ofstream fout;
        fout.open("OUTPUT.TXT");
        i = searchLexemes(input, i, 1, &fout);
    }
    

    【讨论】:

    • 指针是一种变量。你需要传入的是fout的地址,这就是你需要使用&的原因。您传入的这个地址只能被您的函数定义识别为指针类型变量。这样,当函数修改 fout 时,你的 main 中的那个就会改变。正如您告诉函数访问该内存一样。否则,当您正常传入一个变量时,该函数会为自己制作一个副本。
    • 作为函数签名中的简单引用std::ofstream &amp;fout 也可以,并使searchLexemes() 的实现代码更易于编写和阅读。
    • 投反对票,因为这里的代码存在内存泄漏(因为fout 不是deleted)。
    • @cybermonkey 废话,没有泄漏。 fout 从未使用 new 创建。如果您投反对票,请有正当理由。
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2011-12-26
    • 2020-01-24
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多