c++ - 找不到合适的复制构造函数
问题描述
class CTextureBuffer {
public:
int m_width;
int m_height;
void* m_data;
CTextureBuffer (int width = 0, int height = 0, void * data = nullptr)
: m_width (width), m_height (height), m_data (data) {}
CTextureBuffer (CTextureBuffer& other)
: m_width (other.m_width), m_height (other.m_height), m_data (other.m_data) {}
CTextureBuffer operator= (CTextureBuffer other) {
m_width = other.m_width;
m_height = other.m_height;
m_data = other.m_data;
return *this;
}
};
void InitTexBuf (SDL_Surface* image) {
CTextureBuffer texBuf;
texBuf = CTextureBuffer (image->w, image->h, image->pixels);
}
Error C2679 binary '=': no operator found which takes a right-hand operand
of type 'CTextureBuffer' (or there is no acceptable conversion)
SDL_Surface::w, ::h 是整数。SDL_Surface::pixels 是无效的 *。就这样没有人抱怨我没有解释参数。
我不知道如何在这里编写适当的复制构造函数。对我来说,CTextureBuffer 中似乎有编译器需要的一切。
顺便说一句,我实际上在做的是这个(wip):
// read a bunch of textures for a cubemap
// omitting a filename means "reuse the previous texture for the current cubemap face"
// first filename must not be empty
bool CTexture::Load (CArray<CString>& fileNames, bool flipVertically) {
// load texture from file
m_fileNames = fileNames;
CTextureBuffer texBuf;
for (auto const& fileName : fileNames) {
if (fileName->Length ()) {
SDL_Surface * image = IMG_Load ((char*) (*fileName));
if (!image) {
fprintf (stderr, "Couldn't find '%s'\n", (char*) (*fileName));
return false;
}
texBuf = CTextureBuffer (image->w, image->h, image->pixels);
}
m_buffers.Append (texBuf);
}
return true;
}
解决方案
您的复制构造函数应该接受一个const&
CTextureBuffer (CTextureBuffer& other) // wrong
CTextureBuffer (CTextureBuffer const& other) // right
您的复制赋值运算符也一样,它应该返回一个引用
CTextureBuffer operator= (CTextureBuffer other) // wrong
CTextureBuffer& operator= (CTextureBuffer const& other) // right
还要遵守 5 规则,您还需要定义移动构造函数和移动赋值运算符
CTextureBuffer(CTextureBuffer&& other) = default; // move construct
CTextureBuffer& operator=(CTextureBuffer&& other) = default; // move assignment
推荐阅读
- c# - Automapper - 如何在深层应用 ForMember 配置
- asp.net-web-api - FormatAttribute 需要正斜杠来执行不带参数的操作
- azure-active-directory - 如何将 AppRoleAssignments 与“Graph explorer API”中的应用程序匹配
- ios - 在 Objective-C 中操作图像时发生内存泄漏
- java - 在詹金斯上触发“立即构建”并显示控制台输出的程序
- c# - 如何使用 ssh.net 将格式化的 JSON 写入文本文件?
- python - 如何找到最小距离..当两点属于相同距离时
- reactjs - 如何使用 Jest 模拟 axios 发布请求?
- c++ - Lambda 表达式(向量之和)
- python - 分别绘制所有 pandas 数据框列