gpt4 book ai didi

c++ - (隐式声明)不能被引用——它是一个被删除的函数

转载 作者:行者123 更新时间:2023-12-04 15:29:54 26 4
gpt4 key购买 nike

使用以下代码,我面临一个问题。

ABC.h

namespace abcd
{
class ABC
{
public:
ABC() = delete;
ABC(const std::string& filename);
virtual ~ABC();
ABC(const ABC&) = delete;
ABC(ABC&&) = default;
};
}

XYZ.h
using namespace abcd;

class XYZ
{
public:
void func();
private:
ABC obj;
ABC maskfilename(std::string filename);
};

XYZ.cpp
XYZ::func()
{
obj = maskfilename("abcd.txt"); //Error
}

abcd::ABC XYZ::maskfilename(string filename)
{
abcd::ABC ret;
// blah blah...
return ret;
}

错误:

"abcd::ABC::operator=(const abcd::ABC &)" (declared implicitly) cannot be referenced -- it is a deleted function



我知道它只是移动构造函数类( ABC )。

使用它的正确方法是什么?我想保留来自 maskfilename() 的返回值在 XYZ类,所以可以在 XYZ的其他函数中使用类(class)。

我该如何解决这个错误?

最佳答案

这是类ABC的声明:

namespace abcd
{
class ABC
{
public:
ABC() = delete;
ABC(const std::string& filename);
virtual ~ABC();
ABC(const ABC&) = delete;
ABC(ABC&&) = default;
};
}

引用 MSVC 错误 C2280 :

The compiler detected an attempt to reference a deleted function. Thiserror can be caused by a call to a member function that has beenexplicitly marked as = deleted in the source code. This error can alsobe caused by a call to an implicit special member function of a structor class that is automatically declared and marked as deleted by thecompiler. For more information about when the compiler automaticallygenerates default or deleted special member functions, see Specialmember functions.


在您的情况下,除了转换构造函数之外,您的类 ABC只有一个移动构造函数。编译器已隐式声明复制赋值运算符和移动赋值运算符为已删除。这就是您收到此错误的原因。这一行试图调用您删除的复制赋值运算符:
obj = maskfilename("abcd.txt"); //Error
由于您希望您的类成为仅移动类,因此只需声明一个移动赋值运算符,然后同一行将调用您的移动赋值运算符。那么 maskfilename的右值退货将移至 obj .
这是您的类的重新设计实现 ABC :
class ABC
{
public:
ABC() = delete;
ABC(std::string filename) : mFilename(std::move(filename)) {}
virtual ~ABC() = default;
ABC(const ABC&) = delete;
ABC& operator= (const ABC&) = delete;
ABC(ABC&&) = default;
ABC& operator= (ABC&&) = default;
std::string GetFilename() const { return mFilename; }

private:
std::string mFilename;
};

在您的类(class) XYZ你不能有成员变量 obj类型 ABC因为删除了默认构造函数。如果你需要在 XYZ的其他方法中使用这样的对象你可以有一个指向 ABC 的唯一指针反而。所以我会像这样改变它:
XYZ.h:
#include "ABC.h"
#include <memory>

class XYZ
{
public:
void func();

private:
std::unique_ptr<ABC> obj;
std::unique_ptr<ABC> maskfilename(std::string filename);
};
XYZ.cpp:
void XYZ::func()
{
obj = std::move(maskfilename("abcd.txt"));
}

std::unique_ptr<ABC> XYZ::maskfilename(std::string filename)
{
std::unique_ptr<ABC> ret = std::make_unique<ABC>(filename);
// blah blah...
return ret;
}

关于c++ - (隐式声明)不能被引用——它是一个被删除的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61435943/

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