【问题标题】:C++ operator overloading to do double * object [duplicate]C ++运算符重载以执行双*对象[重复]
【发布时间】:2020-10-07 13:03:08
【问题描述】:

我目前正在编写一个类来进行一系列矩阵运算,其中之一是将矩阵与一个数字相乘。我成功制作了 Matrix * 2 p.e.但我想做 2 * 矩阵。那可能吗?如何?

这是第一个运算符重载 (Matrix * double) 的签名: Matrix Matrix::operator* (const double& b)

【问题讨论】:

标签: c++


【解决方案1】:

所以,你可以像这样重载operator*

class t
{
private:
    int f;
public:
    t(const int& i) : f(i) {}
    friend t& operator*(const int& a, t&);
    int get() const
    {
        return f;
    }
};

t& operator*(const int& a, t& obj)
{
    obj.f *= a;
    return obj;
}

int main()
{
    t obj(5);
    obj = 2 * obj;
    std::cout << obj.get();
}

结果:10

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2012-12-22
    • 2016-09-26
    • 2012-04-21
    相关资源
    最近更新 更多