c++ - 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;
}
解决方案
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
对象。您必须改为将其设为非成员函数。
推荐阅读
- idris - 为什么 Idris 给我以下代码的类型不匹配错误?
- python-3.x - 使用 SSH 在多个 EC2 实例上运行 dispynode.py 似乎可行,但实际上并没有
- apache-spark - 有没有办法在数据帧级别优化 dataframe.writer.partitionBy ?
- coding-style - 干净的架构——在哪里放置输入验证逻辑?
- angular - 将输入值添加到Angular中的动态
- tcl - 为什么文件名没有正确呈现
- python - 如何在从 input() 获取输入时保留输入的换行符?
- reactjs - 在 React 中使用 leaflet-geotiff 的问题
- neo4j - 在 Cypher Neo4j 中查找并计算从一个节点开始不超过特定长度的所有可能路径
- c# - 使用 Mupen64Plus 非托管 C dll API 命令填充 C# 结构