c++ - 错误 : initial value of reference to non-const must be an value

标签 c++ operator-overloading operators

class A
{

public:

    int v;
    A * p;
    A& operator*(const A& a)
    {
        return this->v*a.v// here is a red line under this say error initial value of reference to non-const must be an value
    }
    ~A()
    {
        this;
    }
};

int main()
{
    A a;
    a.p = new A;
    delete a.p;
    return 0;

    system("pause");
    return 0;
}

重载 * 运算符 我不能用它来表示对象本身。为什么会这样。

最佳答案

当然它说它必须是一个左值。您正在尝试返回对临时文件的引用。这是恶业。

此外,这根本不是你想要的。乘法运算符绝对应该返回一个值,而不是一个引用。

不确定您的构造函数是什么样的,但假设它采用整数:

A operator * (A const& other) const
{
    return A{ v * other.v};
};

编辑:

实际上你应该更进一步:

struct A
{
    A& operator *= (A const& other) { v *= other.v; return *this; }
    A(int i) : v(i) {}
private:
    int v;
}

A operator * (A lh, A const& rh)
{
   A res{std::move(lh)};
   res *= rh;
   return res;
}

关于c++ - 错误 : initial value of reference to non-const must be an value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001702/

相关文章:

C++ 运算符重载 >= 有 2 个不同的返回值

c++ - 返回内存映射文件后数据丢失

c++ - 帮助宏功能

c++ - 为什么我不能将C++转换运算符作为非成员函数重载于类之外?

c++ - 不匹配 ‘operator-’

javascript - Node.getAttribute 的运算符计算不一致

c++ - 如何扩展 STL 类以拥有自己的方法?

c++ - 实现访问者模式,同时允许不同的返回类型的函数

perl - || =的含义是什么

Java 运算符优先级