Обособяване на класове
Чете се информация за компютри, съдържаща:
име на модел | name | OmniBook XE |
цена | price | 5660 |
оценка | score | 76 |
OmniBook XE
5660
76
ACMA P300
1095
75
AMAX Poewrstation
1999
78
Търси се продукта с най-голямо отношение оценка/цена.
#include <iostream>
#include <string>
using namespace std;
int main()
{ string best_name = "";
double best_price = 0;
int best_score = 0;
bool more = true;
while (more)
{ string next_name;
double
next_price;
int next_score;
cout <<
"Please enter the model name: ";
getline(cin,
next_name);
cout <<
"Please enter the price: ";
cin >>
next_price;
cout <<
"Please enter the score: ";
cin >>
next_score;
string
remainder; /* read remainder of line */
getline(cin,
remainder);
if (next_price
!= 0)
{
if (best_price == 0 or
next_score/next_price > best_score/best_price)
{ best_name = next_name;
best_score = next_score;
best_price = next_price;
}
}
cout <<
"More data? (y/n) ";
string
answer;
getline(cin,
answer);
if (answer
!= "y") more = false;
}
cout << "The best bang
for the buck is " << best_name
<<
" (Score: " << best_score
<<
" Price: " << best_price << ")\n";
return 0;
}
Интерфейс и капсулиране
#include <iostream>
#include <string>
using namespace std;
class Product {
public: /*интерфейс*/
Product();
/*създава нов продукт*/
void read();
/*чете продукт*/
bool is_better_than(Product
b) const; /*сравнява*/
void print() const;
/*отпечатва*/
private: /*капсулиране*/
string name;
/*скрити данни*/
double price;
/*скрити данни*/
int score;
/*скрити данни*/
};
int main()
{ Product best;
bool more = true;
while (more)
{ Product next;
next.read();
if (next.is_better_than(best))
best = next;
cout <<
"More data? (y/n) ";
string
answer;
getline(cin,
answer);
if (answer
!= "y") more = false;
}
cout << "The best bang
for the buck is ";
best.print();
return 0;
}