Jos*_*yan 6 c++ xcode operator-overloading pre-increment post-increment
我有一个头文件和一个.cpp文件.我试图实现前缀和后缀运算符重载,但我在设置重载时不断收到此错误.
fraction.h
#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
using namespace std;
class Fraction
{
public:
Fraction();
Fraction(int, int);
int getTop() {return m_top;}
int getBottom() {return m_bottom;}
void set(int t, int b) {m_top=t; m_bottom=b; reduce();
}
protected:
private:
void reduce();
int gcf(int, int);
int m_top;
int m_bottom;
};
Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);
#endif
Run Code Online (Sandbox Code Playgroud)
Main.cpp的
#include <iostream>
using namespace std;
#include "fraction.h"
int main {
cout << "The fraction is" << f;
cout << "The output of ++f is " << (++f) << endl;
cout << "The fraction is" << f;
cout << "The output of f++ is " << (f++) << endl;
cout << "The fraction is" << f;
return 0;
}
Fraction& Fraction::operator ++ (Fraction){
// Increment prefix
m_top += m_bottom;
return *this;
}
Fraction Fraction::operator ++ (Fraction, int){
//Increment postfix
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的两个错误:
prefix error: "Parameter of overloaded post-increment operator must have type 'int' (not 'Fraction')"
postfix error: "Overloaded 'Operator++' must be a unary or binary operator (has 3 parameters)"
Run Code Online (Sandbox Code Playgroud)
前缀错误实际上是我的ide错误吗?我知道后增量必须是'int',但我试图做一个预增量.我用xcode.
您将类外部的运算符声明为非类函数
Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);
Run Code Online (Sandbox Code Playgroud)
但是,然后您尝试像类成员函数一样定义它们
Fraction& Fraction::operator ++ (Fraction){
// Increment prefix
m_top += m_bottom;
return *this;
}
Fraction Fraction::operator ++ (Fraction, int){
//Increment postfix
}
Run Code Online (Sandbox Code Playgroud)
通过以下方式将它们声明为类成员函数
class Fraction
{
public:
Fraction & operator ++();
Fraction operator ++( int );
//...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,预自增运算符的定义可以如下所示
Fraction & Fraction::operator ++(){
// Increment prefix
m_top += m_bottom;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
或者将它们声明为非类函数,它们是类的友元,因为它们需要访问类的私有数据成员
class Fraction
{
public:
friend Fraction & operator ++( Fraction & );
friend Fraction operator ++( Fraction &, int );
//...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,预自增运算符的定义可以如下所示
Fraction & operator ++( Fraction &f ){
// Increment prefix
f.m_top += f.m_bottom;
return f;
}
Run Code Online (Sandbox Code Playgroud)