1. Напишите программу, которая объявляет класс с именем Employee (Служащие) с такими переменными-членами: age (возраст), yearsOfService (стаж работы) и Salary (зарплата).
class Employee
{
int Age;
int YearsOfService;
int Salary;
};
2. Перепишите класс Employee, чтобы сделать данные-члены закрытыми и обеспечить открытые методы доступа для чтения и установки всех данных-членов.
class Employee
{
public:
int GetAge() const;
void SetAge(int age);
int GetYearsOfService() const;
void SetYearsOfService(int years);
int GetSalary() const;
void SetSalary(int salary);
private:
int Age;
int YearsOfService;
int Salary;
};
3. Напишите программу с использованием класса Employee, которая создает два объекта класса Employee; устанавливает данные-члены age, YearsOfService и Salary, а затем выводит их значения.
int main()
{
Employee John;
Employee Sally;
John.SetAge(30);
John.SetYearsOfService(5);
John.SetSalary(50000);
Sally.SetAge(32);
Sally.SetYearsOfService(8);
Sally.SetSalary(40000);
cout << "At AcmeSexist company, John and Sally have the same job.\n";
cout << "John is " << John.GetAge() << " years old and he has been with";
cout << "the firm for " << John.GetYearsOfService << " years.\n";
cout << "John earns $" << John.GetSalary << " dollars per year.\n\n";
cout << "Sally, on the other hand is " << Sally.GetAge() << " years old and has";
cout << "been with the company " << Sally.GetYearsOfService;
cout << " years. Yet Sally only makes $" << Sally.GetSalary();
cout << " dollars per year! Something here is unfair.";
return 0;
}
4. На основе программы из упражнения 3 создайте метод класса Employee, который сообщает, сколько тысяч долларов зарабатывает служащий, округляя ответ до 1 000 долларов.
float Employee:GetRoundedThousands() const
{
return (Salary+500) / 1000;
}
5. Измените класс Employee так, чтобы можно было инициализировать данные-члены
age, YearsOfService и Salary в процессе "создания" служащего.
class Employee
{
public:
Employee(int Age, int yearsOfService, int salary);
int GetAge() const;
void SetAge(int Age);
int GetYearsOfService() const;
void SetYearsOfService(int years);
int GetSalary() const;
void SetSalary(int salary);
private:
int Age;
int YearsOfService;
int Salary;
};
6. Жучки: что неправильно в следующем объявлении?
class Square
{
public:
int Side;
}
Объявления классов должны завершаться точкой с запятой.
7. Жучки: что весьма полезное отсутствует в следующем объявлении класса?
class Cat
{
int GetAge() const;
private:
int itsAge;
};
Метод доступа к данным GetAge() является закрытым по умолчанию. Помните: все члены класса считаются закрытыми, если не оговорено иначе.
8. Жучки: какие три ошибки обнаружит компилятор в этом коде?
class TV
{
public:
void SetStation(int Station);
int GetStation() const;
private:
int itsStation;
};
main()
{
TV myTV;
myTV.itsStation = 9;
TV.SetStation(10);
TV myOtherTv(2);
}
Нельзя обращаться к переменной itsStation непосредственно. Это закрытая пере- менная-член.
Нельзя вызывать функцию-член SetStation()npHMO в классе. Метод SetStation() можно вызывать только для объекта.
Нельзя инициализировать переменную-член itsStation, поскольку в программе не определен нужный для этого конструктор.
Комментариев нет:
Отправить комментарий