首页 > 解决方案 > 找不到合适的复制构造函数

问题描述

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;
}

标签: c++copy-constructor

解决方案


您的复制构造函数应该接受一个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

推荐阅读