这是我的主要功能
#include <iostream>
#include "FlyingPoints.h"
using namespace std;
void read(const char* msg, FlyingPoints& f)
{
int inPoints, outPoints;
cout << "Enter " << msg << endl;
cout << "Enter number of incoming flying points: ";
cin >> inPoints;
cout << "Enter number of spent flying points: ";
cin >> outPoints;
f = FlyingPoints(inPoints, outPoints);
}
int main()
{
FlyingPoints left, right, result, ref;
cout << "Flying Points Calculator\n";
cout << "========================\n";
read("Left Operand...", left);
read("Right Operand...", right);
cout << "Result: " << endl;
left.display();
cout << " + ";
right.display();
cout << " = ";
result = left + right;
result.display();
cout << endl;
read("2nd Right Operand...", right);
cout << "Result: " << endl;
result.display();
cout << " += ";
right.display();
cout << " => ";
result += right;
result.display();
cout << endl;
read("Reference...", ref);
if (result == ref){
cout << "Result == Reference" << endl;
} else {
cout << "Result != Reference" << endl;
}
return 0;
}
头文件
class FlyingPoints{
int inPoints;
int outPoints;
void updatebalance();
public:
FlyingPoints();
FlyingPoints(int, int);
void display();
FlyingPoints& operator+=(const FlyingPoints&);
friend bool operator==(const FlyingPoints&, const FlyingPoints&);
};
FlyingPoints operator+(const FlyingPoints&, const FlyingPoints&);
和.cpp文件
#include <iostream>
#include "FlyingPoints.h"
using namespace std;
void FlyingPoints::updatebalance(){
if(inPoints > outPoints){
inPoints = inPoints - outPoints;
outPoints = 0;
}else{
outPoints = inPoints - outPoints;
inPoints = 0;
}
}
FlyingPoints::FlyingPoints(){
inPoints = 0;
outPoints = 0;
}
FlyingPoints::FlyingPoints(int in, int out){
inPoints = in;
outPoints = out;
}
void FlyingPoints::display(){
cout << inPoints << " points available to fly." << outPoints << " points spent." << endl;
}
FlyingPoints& FlyingPoints::operator+=(const FlyingPoints& f){
inPoints += f.inPoints;
outPoints += f.outPoints;
updatebalance();
return *this;//why do we return this?*this refers to the operator?
}
FlyingPoints operator+(const FlyingPoints& a, const FlyingPoints& b){
//inPoints = a.inPoints + b.inPoints;
//outPoints = a.outPoints + b.outpoints;
return a + b;
}
bool operator==(const FlyingPoints& first, const FlyingPoints& second){
if(first.inPoints == second.inPoints && first.outPoints == second.outPoints){
return true;
} else {
return false;
}
}
当我跑步时会发生这种情况。 飞点计算器
======================== 输入左操作数......
输入传入飞行点数:500
输入用完的飞行点数:300
输入右操作数...
输入传入飞行点数:200
输入用完的飞行点数:100
结果:
500点可用于飞行.3点花费。
分段错误
我似乎无法分辨这个分段错误来自哪里,可以
有人帮忙吗? cout可能是原因吗? - 谢谢答案 0 :(得分:2)
问题的原因是operator+()
无条件地调用自身,因此无限递归。
引用OP。
FlyingPoints operator+(const FlyingPoints& a, const FlyingPoints& b){
//inPoints = a.inPoints + b.inPoints;
//outPoints = a.outPoints + b.outpoints;
return a + b;
}