错误:使用已删除的函数'ClassName :: ClassName(const ClassName&)'

时间:2018-11-27 03:46:13

标签: c++ g++

我在编译时总是收到此错误,但是我不知道为什么。我看过this个帖子和this一个帖子,但它们似乎是不同的问题。

相关代码结构为:

// main.cpp

#include "MyClass.h"

int main() {
    MyClass newClass = MyClass();
}


// MyClass.h

#include <string>
#include <sstream>
#include <vector>
using namespace std;
class Node;

class MyClass {
private:
    vector<Node*> nodes;
    int number;
    stringstream fileInfo;
public:
    MyClass();
    ~MyClass();
};


// MyClass.cpp

#include "MyClass.h"

MyClass::MyClass() {
    number = 1;
}

MyClass::~MyClass() {}

编译时出现的错误是:

main.cpp: In function 'int main()':
main.cpp:4:29: error: use of deleted function 'MyClass(const MyClass&)'
  MyClass new Class = MyClass();
                              ^
In file included from main.cpp:1:0:
MyClass.h:7:7: note: 'MyClass::MyClass(const MyClass&)' is implicitly deleted because the definition would be ill-formed:
  class MyClass {
        ^
MyClass.h:7:7: error: use of deleted function 'std::__cxx11::basic_stringstream<_CharT, _Traits, _Alloc>::basic_stringstream(const std::__cxx11:basic_stringstream<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
In file included from MyClass.h:2:0,
                 from main.cpp:1:
/usr/included/c++/5/sstream:721:7: note: declared here
        basic_stringstream(const basic_stringstream&) = delete;
        ^

我尝试初始化构造函数中的所有类成员,但是并没有改变错误。除此之外,我想不出什么问题。

1 个答案:

答案 0 :(得分:2)

问题在于您的类不可复制,因为它包含一个{u'rowData': [ {u'values': [{}, {u'note': u'B1 notes'}, {}, {}, {u'note': u'E1 notes'}]}, {}, {}, {u'values': [{}, {}, {}, {u'note': u'D4 notes'}]}, {}, {}, {u'values': [{}, {u'note': u'B7 notes'}]} ] } (它本身是不可复制的)。这导致其副本构造函数被删除,这是编译器试图告诉您的。要解决此问题,只需不要在''函数中使用复制初始化语法。

std::stringstream