클래식 클래스 연산자 오버로딩과 클래스 정의에 대해 많은 의문이 생길 것입니다. 왜 그렇게 복잡한 지에 대해서는 많은 세부 사항과 사용의 간편함이 관련되어 있습니다.
// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Lap_time class represents minutes and seconds
struct lap_time {
int minutes;
int seconds;
// Default constructors
lap_time() : minutes(0),seconds(0) { }
lap_time(const string& str) {
stringstream ss(str);
string value;
if (std::getline(ss, value, ':'))
minutes = stoi(value);
if (std::getline(ss, value, ':'))
seconds = stoi(value);
}
lap_time(int m, int s) : minutes(m), seconds(s) { }
// input operator overload
friend istream& operator >> (istream& is, lap_time&);
// output operator overload
friend ostream& operator << (ostream& os, lap_time&);
// Time multiply operation
lap_time operator*(const int& x) {
int time = (this->minutes) * 60 + this->seconds;
time = time * 2;
return lap_time(time/60, time % 60);
}
};
// input operator overload declaration
istream& operator>>(istream& is, lap_time& lt)
{
string laptime;
is >> laptime;
stringstream ss(laptime);
string value;
if (std::getline(ss, value, ':'))
lt.minutes = stoi(value);
if (std::getline(ss, value, ':'))
lt.seconds = stoi(value);
return is;
}
// ouput operator overload declaration
ostream& operator<<(ostream& os, lap_time& lt)
{
stringstream ss;
ss << lt.minutes << ":" << lt.seconds;
os << ss.str();
return os;
}
// getline function overload to read lap_time
void getline(std::istream& is, lap_time& lt)
{
string laptime;
is >> laptime;
stringstream ss(laptime);
string value;
if (std::getline(ss, value, ':'))
lt.minutes = stoi(value);
if (std::getline(ss, value, ':'))
lt.seconds = stoi(value);
}
int main()
{
string car_number1;
string car_number2;
string car_number3;
string car_color1;
string car_color2;
string car_color3;
lap_time race_time1;
lap_time race_time2;
lap_time race_time3;
cout << "We are doing a 2 lap race." << ' ' << endl;
//Data for car 1
cout << "Enter a number for the first race car: " << endl;
cin >> car_number1;
cin.ignore();
cout << "Enter a color for car number " << car_number1 << endl;
getline(cin, car_color1);
cout << "Enter a lap time in MM:SS: for the " << car_color1 << ' ' << car_number1 << ' ' << "car" << endl;
getline(cin, race_time1);
cout << "Single Lap race time is :" << race_time1 << endl;
// I do not think you should multiply by two unless assuming both laps equal timing.
cout << "Two lap race time is : " << (race_time1 * 2) << endl;
}
을 사용하는 문자열을? 단순히'int a; cin >> a는 트릭을했을 것입니다. –
처음부터'int'를 사용하여 문제를 해결하십시오. –
그리고 먼저 문자열을 읽더라도'std :: stoi'가 있습니다. – Dutow