尝试使用*this引用已删除的函数

3

我一直在为俄勒冈理工大学的C++课程项目工作,但我遇到了一个错误,即使我的教授也无法帮助我。 我一直在尝试使用移动构造函数,但我不断收到以下错误:

函数“Shapes :: operator =(const Shapes&)”(隐式声明)不能被引用-第31行

“Shapes :: operator =(const Shapes&)”:尝试引用已删除的函数-第31行

// Shapes.h

#ifndef LAB1_SHAPES_H
#define LAB1_SHAPES_H

class Shapes {
protected:
    float m_width;
    float m_area;
    float m_perimeter;
public:
    Shapes() {
        m_width = 0;
        m_area = m_width * m_width;
        m_perimeter = 4 * m_width;
    }

    Shapes(float x) {
        if (x > 0) {
            m_width = x;
        }

        m_area = m_width * m_width;
        m_perimeter = 4 * m_width;
    }

    Shapes(Shapes&& move) noexcept {
        *this = move;
    }

    Shapes(const Shapes& copy) {
        m_width = copy.m_width;
        m_area = m_width * m_width;
        m_perimeter = 4 * m_width;
    }

    float getWidth() const {
        return m_width;
    }
    float getArea() const {
        return m_area;
    }
    float getPerimeter() const {
        return m_perimeter;
    }
};

#endif //LAB1_SHAPES_H

错误发生在第31行 - "* this = move;" - Cameron McHatton
1个回答

4
Shapes(Shapes&& move) noexcept

你为这个类声明了一个移动构造函数。

导致了一个已删除的复制赋值运算符。这意味着默认情况下不会为您提供它:

An implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:

...

T has a user-declared move constructor; 

...

就是这样。如果想要解决此问题,您需要定义自己的operator=重载函数,来实现此类别具有该操作符时应当执行的操作。


2
“为了解决这个问题,您需要定义自己的operator=重载”,或者干脆摆脱移动构造函数,因为在这个类中它是无用的,因为float值不能被“移动”。" - Remy Lebeau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接