编译错误“被隐式删除,因为默认定义格式错误”

我知道已经有人问过类似的问题,但我无法通过查看类似的帖子找到答案。这是我的问题的最小工作示例,其中包含以下 C++ 代码:

#include <iostream>
#include <cstdio>
#include <fstream>

using namespace std;

class File{

 public:
  fstream value;
  string name;
  unsigned int number_of_lines;
  
  
};


void print_filename(File file){

  cout << "Name of file is " << file.name << "n";
  
}


int main(void){

  File file;
  print_filename(file);
  

  cout << "n";
  return(0);
    
}

当我编译时,我收到错误:

example.cpp: In function ‘int main()’:
example.cpp:28:22: error: use of deleted function ‘File::File(const File&)’
   print_filename(file);
                      ^
example.cpp:7:7: note: ‘File::File(const File&)’ is implicitly deleted because the default definition would be ill-formed:
 class File{
       ^~~~
example.cpp:7:7: error: use of deleted function ‘std::basic_fstream<_CharT, _Traits>::basic_fstream(const std::basic_fstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’
In file included from example.cpp:3:0:
/usr/local/include/c++/7.2.0/fstream:925:7: note: declared here
       basic_fstream(const basic_fstream&) = delete;
       ^~~~~~~~~~~~~
example.cpp:18:6: note:   initializing argument 1 of ‘void print_filename(File)’
 void print_filename(File file){
      ^~~~~~~~~~~~~~

你知道为什么吗?感谢您的帮助

回答

能够读取错误是一项宝贵的技能!我们开始做吧。


error: use of deleted function ‘File::File(const File&)’

您正在调用File不存在的复制构造函数。

note: ‘File::File(const File&)’ is implicitly deleted

编译器已隐含地选择禁止File.

error: use of deleted function ‘basic_fstream(const std::basic_fstream&)

这是因为复制构造函数需要fstream已删除的复制构造函数。

 note: declared here
         basic_fstream(const basic_fstream&) = delete;
         ^~~~~~~~~~~~~

那是明确声明不允许复制构造的代码。

note:   initializing argument 1 of ‘void print_filename(File)’
     void print_filename(File file){

这是您的代码中存在问题的地方。


正如评论的那样,解决方案是不制作副本。不需要。

而是通过引用传递。


以上是编译错误“被隐式删除,因为默认定义格式错误”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>