首页 > 解决方案 > no operator " *= " 匹配这些操作数 测试运算符重载时产生的错误 *=

问题描述

尝试输出运算符重载的结果时收到以下错误消息*=

no operator "*=" matches these operands   
operand types are: ifs::units::Feet *= ifs::units::Feet

cout 语句的这一部分产生了错误

(comp19 *= comp20)

我知道这是不允许的,但我不知道如何获取*=操作员生成的输出。此测试适用于 ,+=但不适用于*=,很可能是因为在这种情况下rhs是 a double,但我不允许将其更改为一种Ftr类型。

如何使用给定的定义获得结果?有什么建议么?

以下是文件:

Ftr.h

#ifndef __FTR_H
#define __FTR_H


#include <cstdint>

namespace fun::calc 
{

    class Ftr
    {
    
    public:

        Ftr() = delete;
        explicit Ftr(double Ftr) noexcept;
        ~Ftr() noexcept;
        Ftr(const Ftr &other) = default;
        Ftr(Ftr &&other) = default;

        double getNum() const noexcept;
        Ftr operator+(const Ftr &rhs) const;
        
        Ftr& operator+=(const Ftr &rhs);
        Ftr& operator*=(const double &rhs);
        
        
    private:
        
        double m_Num;
        
    };

}
#endif;

Ftr.cpp

#include "Ftr.h"
#include <iostream>
#include <string>

namespace fun::calc 

{

// FUNCTION:    Destructor

    Ftr::~Ftr() {
    }

// FUNCTION:    Constructor

    Ftr::Ftr(double Ftr) noexcept {

    }

// FUNCTION:    getNum

    double Ftr::getNum() const noexcept {
        return m_Num;
    }

// FUNCTION:    Overloaded Addition 

    Ftr Ftr::operator+(const Ftr & rhs) const {
        return Ftr(m_Num + rhs.m_Num);
    }
    
// FUNCTION:    Overloaded Multiplication

    Ftr& Ftr::operator*=(const double & rhs) {
        m_Num *= rhs;
        return *this;
    }

}

主项目.cpp

#include "pch.h"

#include "Ftr.h"
#include <iostream>
#include <string>

using namespace fun::calc;

int main()
//mainFtrTest
{
    std::cout << "Ftr Class Testing Started ! \n\n";

        Ftr c(4);
        std::cout << "Ftr = " << c.getNum() << "\n\n"; 
        
    //  Addition operator
        Ftr add1(8);
        Ftr add2(7);
        Ftr total = add1 + add2;
        std::cout << add1.getNum() << " + " << add2.getNum() << " = " << total.getNum() <<"\n\n";
        
    //  Multiplication operator 
        Ftr comp19(9);
        Ftr comp20(7);
        std::cout << comp19.getNum() << " *= " << comp20.getNum() << " = " << (comp19 *= comp20);
    
        return 0;
}

标签: c++c++17

解决方案


Ftr& Ftr::operator*=(const double & rhs)表示运算符的右侧*=应该是 a double。但是,在您的主要功能中,您正在做comp19 *= comp20右手边是一个Ftr对象的地方。你可以做comp19 *= comp20.getNum()你的右手边 a double,但我认为你真正想要的是声明:

Ftr& operator*=(const Ftr& rhs);

并定义:

Ftr& Ftr::operator*=(const Ftr& rhs){
    m_Num *= rhs.m_Num;
    return *this;
}

这将*=成功,但您还有另一个问题:

<< (comp19 *= comp20);

运算符的右侧<<是一个Ftr对象。你需要另一个重载:

std::ostream& operator<<(std::ostream& os, const fun::calc::Ftr& rhs){
    os << rhs.getNum();
    return os;
}

这个重载不能进入类定义,因为操作符的左边<<是一个std::ostream对象。您必须改为将其设为非成员函数。


推荐阅读