gpt4 book ai didi

c++ - 错误 : use of deleted function 'ClassName::ClassName(const ClassName&)'

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:26 28 4
gpt4 key购买 nike

编译的时候一直报这个错,不知道为什么。我看过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;
^

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

最佳答案

问题是您的类不可复制,因为它包含一个 std::stringstream(它本身不可复制)。这导致它的复制构造函数被删除,这是编译器试图告诉你的。要解决此问题,只需不要在 main 函数中使用复制初始化语法即可。

int main() {
MyClass newClass;
}

关于c++ - 错误 : use of deleted function 'ClassName::ClassName(const ClassName&)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492429/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com