我不太确定我的错误在哪里,我也是编程的新手,我知道我打破了很多标准化规则。我在学习。用户输入两个整数并对它们进行比较,它总是报告输入的第一个整数更大,即使它不应该。我想说我的getlength
方法有问题,但此时我不太确定。
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
//Function to find larger value a = first number, b = second number
T findLargerValue(T a, T b) {
return (a>b ? a:b);
}
//Class trip
template <class T>
class Trip {
public:
Trip<T>::Trip();
Trip(T a){
length = a;
}
T operator>(Trip yourTrip);
T getLength() {
return length;
}
private:
T length;
};
// Template function to carry into
/** This is where I seem to be losing my logic, I am trying to push larger of the two objects to the screen but it is only displaying the first user input This is supposed to take in the two bojects created and measure the lengths.**/
template<class T>
T Trip<T>::operator>(Trip yourTrip) {
if (length > yourTrip.getLength()) {
return length;
}
else{
return yourTrip.getLength();
}
}
template<class T>
Trip<T>::Trip()
{
}
int main()
{
// input for integer values
int num1 , num2 ;
cout << "Enter integer value 1: ";
cin >> num1;
cout << endl << endl;
cout << "Enter integer value 2: ";
cin >> num2;
//display message of first two numbers
cout <<"Frist Number was: " << num1 << " Second Number was: " << num2 << "\nThe Larger number of the two is "
<< findLargerValue(num1, num2) << endl << endl;
//input for double values
double num3, num4;
cout << "Enter double value 1: ";
cin >> num3;
cout << endl << endl;
cout << "Enter double value 2: ";
cin >> num4;
//display mesasge of second two numbers
cout << "Frist Number was: " << num3 << " Second Number was: " << num4 << "\nThe Larger number of the two is "
<< findLargerValue(num3, num4) << endl << endl;
// Display message for Trip function/objects
int fTlength, sTlength;
cout << "How many miles was your first trip: ";
cin >> fTlength;
Trip<int> fTrip(fTlength);
cout << endl;
cout << "How many miles was your second trip: ";
cin >> sTlength;
Trip<int> sTrip(sTlength);
Trip<int> tripLonger;
tripLonger = findLargerValue(fTrip, sTrip);
cout << "First trip in miles: " << fTlength << endl << "Second Trip in miles: " << sTlength << endl;
cout << "The longest trip was " << tripLonger.getLength() << " miles." << endl;
system("pause");
return 0;
}
答案 0 :(得分:0)
您错误地重载了operator >
。它应该返回true
的{{1}},但它返回(在这种情况下)一个整数值。它应该是这样的:
false
比较运算符应指示比较是否为真。在您的情况下,它返回template<class T>
bool Trip<T>::operator>(const Trip& yourTrip)
{
return length > yourTrip.length;
}
或length
。当yourTrip.length
为两个对象调用findLargerValue
时,这是一个问题。它检查结果是否为真,并且因为任何不是operator >
的整数是0
,它几乎总是返回第一个对象。如果您输入了一个负数和一个true
,它将返回第二个对象。