“必须有类或枚举类型的参数”实际上是什么意思
我有一个头文件和一个.cpp文件。我需要写我的.h文件的功能,但我得到一个错误,我可以完全完成一个骨架的.cpp文件。
I have a header file and a .cpp file. I an needing to write functions for my .h file but i get an error before i can fully complete a skeleton .cpp file.
Money.h
#ifndef MONEY_H
#define MONEY_H
#include <iostream>
#include <iomanip>
using namespace std;
class Money
{
public:
Money(int dollars, int cents);
Money operator+(const Money& b) const;
Money operator-(const Money& b) const;
Money operator*(double m) const;
Money operator/(double d) const;
void print() const;
private:
int dollars;
int cents;
};
#endif
Money.cpp
Money.cpp
#include "Money.h"
Money::Money(int dollars, int cents){
}
Money operator+(const Money& b) {
}
Money operator-(const Money& b) {
}
Money operator*(double m) {
}
Money operator/(double d) {
}
void print(){
}
错误是乘法和除法运算符:
The errors are with the multiply and divide operators:
Money.cpp:12:25:error:'Money operator *(double)'must have a
argument of class或枚举类型
Money.cpp:12:25: error: 'Money operator*(double)' must have an argument of class or enumerated type
Money.cpp:15:25:error:'Money operator /(double)'必须有类的
参数或枚举类型
Money.cpp:15:25: error: 'Money operator/(double)' must have an argument of class or enumerated type
您没有使用范围解析操作符告诉编译器您正在定义成员函数。它被解释为一个全局运算符重载,它接受两个参数,其中一个必须是类或枚举类型。这基本上意味着您的一个参数必须是用户定义的类型(不是原始类型)或枚举类型,它通过枚举
定义。
You're not using the scope resolution operator to tell the compiler that you are defining a member function. It is instead interpreted as a global operator overload, which takes two arguments, one of which must be of class or enumerated type. This basically means that one of your arguments must either be a user-defined type (type that is not a primitive type) or an enumerated type which is defined through an enum
.
在您的原始代码 Money
只是返回类型;它不会告诉编译器您正在从该类定义成员函数。
In your original code Money
is just the return type; it doesn't tell the compiler that you are defining member function from that class.
这里是您的一行的修复:
Here is a fix for one of your lines:
Money Money::operator+(const Money& b) /*
^^^^^^^ */
{
// ...
}
此外,您的原型和定义也必须匹配cv资格。您的定义缺少 const
限定符...
Moreover, your prototypes and definitions must also match in cv-qualification. Your definitions were missing the const
qualifier...
Money Money::operator+(const Money& b) const /*
^^^^^ */
{
// ...
}
更新:
Update:
发现您的 Money :: operator *
和 Money :: operator /
的定义与其原型不匹配。两个原型都采用 double
,而定义采用 Money const&
。
I also found that your definition for Money::operator*
and Money::operator/
do not match their prototypes. The prototypes for both take a double
while the definitions take Money const&
. You will need to change one to match the other.
// inside Money class
Money operator*(Money const&) const;
Money operator/(Money const&) const;