소개
이 랩에서는 C++ 프로그래밍에서 클래스와 객체를 생성하는 방법을 배우게 됩니다. private 데이터 멤버를 사용하여 클래스를 정의하고, public 멤버 함수를 구현하며, 다양한 매개변수를 가진 생성자를 만들고, 리소스 정리를 위한 소멸자를 작성하고, 접근 지정자를 사용하고, 클래스 간의 상속을 구현하고, 기본 클래스 메서드를 재정의하고, 접근 제어를 위한 friend 함수를 생성하고, static 멤버와 메서드를 사용하는 방법을 배우게 됩니다. 이러한 개념은 C++ 의 객체 지향 프로그래밍의 기본이며, 더 복잡한 애플리케이션을 구축하기 위한 견고한 기반을 제공할 것입니다.
Private 데이터 멤버를 사용하여 클래스 정의하기
C++ 에서 클래스는 객체를 생성하기 위한 청사진입니다. 클래스는 해당 클래스에서 생성된 객체가 가질 속성 (데이터 멤버) 과 메서드 (멤버 함수) 집합을 정의합니다. 클래스는 코드를 구성하고 캡슐화, 상속 및 다형성과 같은 객체 지향 프로그래밍 원칙을 구현하는 데 도움이 됩니다.
C++ 에서 클래스를 정의하는 기본 구문은 다음과 같습니다.
class ClassName {
private:
// Private data members
int dataMember1;
std::string dataMember2;
public:
// Public member functions
void memberFunction1();
int memberFunction2();
};
C++ 에는 클래스 멤버의 가시성과 접근성을 제어하는 세 가지 접근 지정자가 있습니다.
private: private 로 선언된 멤버는 클래스 내에서만 접근할 수 있습니다.public: public 으로 선언된 멤버는 클래스 외부에서 접근할 수 있습니다.protected: protected 로 선언된 멤버는 클래스 내와 파생 클래스 인스턴스에서 접근할 수 있습니다.
이 단계에서는 C++ 에서 private 데이터 멤버를 사용하여 클래스를 정의하는 방법을 배우게 됩니다. private 데이터 멤버는 객체의 내부 상태를 캡슐화하고 보호하는 데 도움이 되는 객체 지향 프로그래밍의 필수 개념입니다.
먼저 WebIDE 를 열고 ~/project 디렉토리로 이동합니다. student.cpp라는 새 파일을 만듭니다.
touch ~/project/student.cpp
WebIDE 에서 student.cpp 파일을 열고 다음 코드를 추가하여 private 데이터 멤버를 가진 Student 클래스를 정의합니다.
#include <iostream>
#include <string>
class Student {
private:
// Private data members
std::string name;
int age;
double gpa;
public:
// We'll add methods to interact with these private members in later steps
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
Student student;
// Note: We can't directly access private members
// student.name = "John"; // This would cause a compilation error
student.displayInfo();
return 0;
}
주요 개념을 자세히 살펴보겠습니다.
Private 데이터 멤버:
private:접근 지정자를 사용하여 선언됩니다.- 클래스 외부에서 직접 접근할 수 없습니다.
- 데이터 보호 및 캡슐화를 제공합니다.
데이터 유형:
std::string name: 학생의 이름을 저장합니다.int age: 학생의 나이를 저장합니다.double gpa: 학생의 평점 평균을 저장합니다.
캡슐화:
- private 멤버는 public 메서드를 통해서만 접근할 수 있습니다.
- 내부 데이터의 직접적인 수정을 방지합니다.
프로그램을 컴파일합니다.
g++ student.cpp -o student
./student
프로그램 실행 시 예시 출력:
Name:
Age: 0
GPA: 0
핵심 사항:
- Private 멤버는 외부 접근으로부터 숨겨집니다.
- 클래스 메서드를 통해서만 수정할 수 있습니다.
- 이는 데이터 무결성 및 제어를 유지하는 데 도움이 됩니다.
Public 멤버 함수 구현하기
이 단계에서는 C++ 에서 public 멤버 함수를 구현하는 방법을 배우게 됩니다. Public 멤버 함수는 private 데이터 멤버에 대한 제어된 접근을 허용하고 클래스 객체와 상호 작용하는 방법을 제공합니다.
WebIDE 에서 student.cpp 파일을 열고 Student 클래스를 수정하여 public 멤버 함수를 포함합니다.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
double gpa;
public:
// Setter methods to modify private data members
void setName(std::string studentName) {
name = studentName;
}
void setAge(int studentAge) {
if (studentAge > 0 && studentAge < 120) {
age = studentAge;
} else {
std::cout << "Invalid age!" << std::endl;
}
}
void setGPA(double studentGPA) {
if (studentGPA >= 0.0 && studentGPA <= 4.0) {
gpa = studentGPA;
} else {
std::cout << "Invalid GPA!" << std::endl;
}
}
// Getter methods to access private data members
std::string getName() {
return name;
}
int getAge() {
return age;
}
double getGPA() {
return gpa;
}
// Display method to print student information
void displayInfo() {
std::cout << "Student Information:" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
Student student;
// Using public member functions to set and get data
student.setName("Alice Johnson");
student.setAge(20);
student.setGPA(3.75);
// Display student information
student.displayInfo();
// Demonstrate getter methods
std::cout << "\nStudent Name: " << student.getName() << std::endl;
std::cout << "Student Age: " << student.getAge() << std::endl;
std::cout << "Student GPA: " << student.getGPA() << std::endl;
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
Student Name: Alice Johnson
Student Age: 20
Student GPA: 3.75
public 멤버 함수에 대한 주요 사항:
- Private 데이터 멤버에 대한 제어된 접근을 제공합니다.
- Setter 는 유효성 검사를 통해 수정을 허용합니다.
- Getter 는 private 데이터를 읽을 수 있도록 합니다.
- 캡슐화 및 데이터 무결성을 유지하는 데 도움이 됩니다.
다양한 매개변수를 가진 생성자 생성하기
이 단계에서는 C++ 에서 다양한 매개변수를 가진 생성자 (constructor) 를 생성하는 방법을 배우게 됩니다. 생성자는 객체가 생성될 때 객체를 초기화하는 특수한 멤버 함수입니다.
WebIDE 에서 student.cpp 파일을 열고 Student 클래스를 수정하여 여러 생성자를 포함합니다.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
double gpa;
public:
// Default constructor
Student() {
name = "Unknown";
age = 0;
gpa = 0.0;
}
// Constructor with name parameter
Student(std::string studentName) {
name = studentName;
age = 0;
gpa = 0.0;
}
// Constructor with name and age parameters
Student(std::string studentName, int studentAge) {
name = studentName;
age = studentAge;
gpa = 0.0;
}
// Full constructor with all parameters
Student(std::string studentName, int studentAge, double studentGPA) {
name = studentName;
age = studentAge;
gpa = studentGPA;
}
// Display method to print student information
void displayInfo() {
std::cout << "Student Information:" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
// Using different constructors
Student student1; // Default constructor
Student student2("Alice Johnson"); // Constructor with name
Student student3("Bob Smith", 22); // Constructor with name and age
Student student4("Charlie Brown", 20, 3.75); // Full constructor
std::cout << "Student 1:" << std::endl;
student1.displayInfo();
std::cout << "\nStudent 2:" << std::endl;
student2.displayInfo();
std::cout << "\nStudent 3:" << std::endl;
student3.displayInfo();
std::cout << "\nStudent 4:" << std::endl;
student4.displayInfo();
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Student 1:
Student Information:
Name: Unknown
Age: 0
GPA: 0
Student 2:
Student Information:
Name: Alice Johnson
Age: 0
GPA: 0
Student 3:
Student Information:
Name: Bob Smith
Age: 22
GPA: 0
Student 4:
Student Information:
Name: Charlie Brown
Age: 20
GPA: 3.75
생성자에 대한 주요 사항:
- 생성자는 클래스와 동일한 이름을 갖습니다.
- 객체 데이터 멤버를 초기화합니다.
- 서로 다른 매개변수를 가진 여러 생성자를 가질 수 있습니다.
- 객체가 생성될 때 자동으로 호출됩니다.
자원 해제를 위한 소멸자 작성
이 단계에서는 C++ 에서 객체가 파괴될 때 리소스를 정리하는 역할을 하는 특수한 멤버 함수인 소멸자 (destructor) 에 대해 배우게 됩니다. 소멸자를 작성하는 방법과 메모리 관리에서 소멸자의 중요성을 이해하는 방법을 보여드리겠습니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 소멸자와 동적 메모리 할당을 포함합니다.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
double gpa;
char* dynamicBuffer; // Simulating dynamic memory allocation
public:
// Constructors
Student() {
name = "Unknown";
age = 0;
gpa = 0.0;
dynamicBuffer = new char[50]; // Allocate dynamic memory
std::cout << "Default Constructor Called" << std::endl;
}
Student(std::string studentName) : name(studentName), age(0), gpa(0.0) {
dynamicBuffer = new char[50];
std::cout << "Parameterized Constructor Called" << std::endl;
}
// Destructor
~Student() {
// Clean up dynamically allocated memory
delete[] dynamicBuffer;
std::cout << "Destructor Called for " << name << std::endl;
}
void displayInfo() {
std::cout << "Student Information:" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
// Demonstrating object creation and destruction
{
std::cout << "Creating first student:" << std::endl;
Student student1("Alice Johnson");
student1.displayInfo();
std::cout << "\nCreating second student:" << std::endl;
Student student2("Bob Smith");
student2.displayInfo();
} // Objects go out of scope here, destructors are called
std::cout << "\nExiting main function" << std::endl;
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Creating first student:
Parameterized Constructor Called
Student Information:
Name: Alice Johnson
Age: 0
GPA: 0
Creating second student:
Parameterized Constructor Called
Student Information:
Name: Bob Smith
Age: 0
GPA: 0
Destructor Called for Bob Smith
Destructor Called for Alice Johnson
Exiting main function
소멸자에 대한 주요 사항:
- 클래스 이름 앞에
~를 붙여 정의합니다. - 객체가 파괴될 때 자동으로 호출됩니다.
- 동적으로 할당된 리소스를 해제하는 데 사용됩니다.
- 메모리 누수를 방지하는 데 도움이 됩니다.
- 반환 유형과 매개변수가 없습니다.
중요한 소멸자 특징:
- 객체가 범위를 벗어날 때 호출됩니다.
- 컴파일러에 의해 자동으로 호출됩니다.
- 동적 메모리 정리에 필수적입니다.
- 시스템 리소스를 효율적으로 관리하는 데 도움이 됩니다.
접근 지정자 사용 (public, private, protected)
이 단계에서는 C++ 의 접근 지정자 (access specifier) 와 클래스 멤버의 가시성 및 접근성을 제어하는 방법에 대해 배우게 됩니다. public, private, protected 접근 수준의 차이점을 살펴보겠습니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 접근 지정자를 시연합니다.
#include <iostream>
#include <string>
class Student {
private:
// Private members: accessible only within the class
std::string name;
int age;
double gpa;
protected:
// Protected members: accessible within the class and its derived classes
std::string school;
public:
// Public members: accessible from anywhere
Student(std::string studentName, int studentAge, double studentGPA) {
name = studentName;
age = studentAge;
gpa = studentGPA;
school = "Default School";
}
// Public method to demonstrate access to private members
void displayInfo() {
std::cout << "Student Information:" << std::endl;
std::cout << "Name: " << name << std::endl; // Accessing private member
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
std::cout << "School: " << school << std::endl;
}
// Public method to modify private members
void updateGPA(double newGPA) {
if (newGPA >= 0.0 && newGPA <= 4.0) {
gpa = newGPA;
}
}
};
class GraduateStudent : public Student {
public:
GraduateStudent(std::string name, int age, double gpa)
: Student(name, age, gpa) {
// Can access protected 'school' member from base class
school = "Graduate School";
}
void displaySchool() {
std::cout << "School: " << school << std::endl;
}
};
int main() {
Student student("Alice Johnson", 20, 3.75);
student.displayInfo(); // Public method accessing private members
// Uncommenting the lines below would cause compilation errors
// student.name = "John"; // Error: Cannot access private member
// student.age = 25; // Error: Cannot access private member
student.updateGPA(3.90); // Modifying private member through public method
student.displayInfo();
GraduateStudent gradStudent("Bob Smith", 25, 3.90);
gradStudent.displayInfo();
gradStudent.displaySchool();
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
School: Default School
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.90
School: Default School
Student Information:
Name: Bob Smith
Age: 25
GPA: 3.90
School: Graduate School
School: Graduate School
접근 지정자에 대한 주요 사항:
private: 멤버는 동일한 클래스 내에서만 접근 가능합니다.protected: 멤버는 클래스 및 파생 클래스 내에서 접근 가능합니다.public: 멤버는 어디에서나 접근 가능합니다.- 데이터 접근을 제어하고 캡슐화를 유지하는 데 도움이 됩니다.
클래스 간 상속 구현
이 단계에서는 C++ 의 상속 (inheritance) 에 대해 배우게 됩니다. 상속은 객체 지향 프로그래밍의 기본 개념으로, 기존 클래스를 기반으로 새로운 클래스를 생성할 수 있게 해줍니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 상속을 시연합니다.
#include <iostream>
#include <string>
// Base class
class Person {
protected:
std::string name;
int age;
public:
// Constructor
Person(std::string personName, int personAge) {
name = personName;
age = personAge;
}
// Method to display basic information
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};
// Derived class: Student inherits from Person
class Student : public Person {
private:
double gpa;
std::string major;
public:
// Constructor that calls base class constructor
Student(std::string studentName, int studentAge, double studentGPA, std::string studentMajor)
: Person(studentName, studentAge) {
gpa = studentGPA;
major = studentMajor;
}
// Additional method specific to Student
void displayStudentInfo() {
// Calling base class method
displayInfo();
std::cout << "GPA: " << gpa << std::endl;
std::cout << "Major: " << major << std::endl;
}
};
// Another derived class: Employee inherits from Person
class Employee : public Person {
private:
std::string company;
double salary;
public:
// Constructor that calls base class constructor
Employee(std::string employeeName, int employeeAge, std::string employeeCompany, double employeeSalary)
: Person(employeeName, employeeAge) {
company = employeeCompany;
salary = employeeSalary;
}
// Additional method specific to Employee
void displayEmployeeInfo() {
// Calling base class method
displayInfo();
std::cout << "Company: " << company << std::endl;
std::cout << "Salary: $" << salary << std::endl;
}
};
int main() {
// Creating objects of derived classes
Student student("Alice Johnson", 20, 3.75, "Computer Science");
std::cout << "Student Information:" << std::endl;
student.displayStudentInfo();
std::cout << "\n";
Employee employee("Bob Smith", 35, "Tech Corp", 75000.0);
std::cout << "Employee Information:" << std::endl;
employee.displayEmployeeInfo();
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
Major: Computer Science
Employee Information:
Name: Bob Smith
Age: 35
Company: Tech Corp
Salary: $75000
상속에 대한 주요 사항:
- 기본 클래스 (Person) 는 공통 속성을 포함합니다.
- 파생 클래스 (Student, Employee) 는 기본 클래스에서 상속받습니다.
- 상속을 위해
: public BaseClassName을 사용합니다. - 파생 클래스에서 새로운 속성과 메서드를 추가할 수 있습니다.
- 파생 클래스에서 기본 클래스 메서드를 사용할 수 있습니다.
기본 클래스 메서드 오버라이딩
이 단계에서는 C++ 에서 기본 클래스 메서드를 재정의하는 방법을 배우게 됩니다. 이를 통해 파생 클래스는 기본 클래스에서 상속된 메서드의 자체 구현을 제공할 수 있습니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 메서드 재정의를 시연합니다.
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
public:
Animal(std::string animalName) : name(animalName) {}
// Virtual keyword allows method to be overridden
virtual void makeSound() {
std::cout << "Some generic animal sound" << std::endl;
}
// Virtual method for displaying information
virtual void displayInfo() {
std::cout << "Animal Name: " << name << std::endl;
}
};
class Dog : public Animal {
private:
std::string breed;
public:
Dog(std::string dogName, std::string dogBreed)
: Animal(dogName), breed(dogBreed) {}
// Override makeSound method
void makeSound() override {
std::cout << "Woof! Woof!" << std::endl;
}
// Override displayInfo method
void displayInfo() override {
// Call base class method first
Animal::displayInfo();
std::cout << "Breed: " << breed << std::endl;
}
};
class Cat : public Animal {
private:
std::string color;
public:
Cat(std::string catName, std::string catColor)
: Animal(catName), color(catColor) {}
// Override makeSound method
void makeSound() override {
std::cout << "Meow! Meow!" << std::endl;
}
// Override displayInfo method
void displayInfo() override {
// Call base class method first
Animal::displayInfo();
std::cout << "Color: " << color << std::endl;
}
};
int main() {
// Create animal objects
Animal genericAnimal("Generic Animal");
Dog myDog("Buddy", "Labrador");
Cat myCat("Whiskers", "Orange");
// Demonstrate polymorphic behavior
std::cout << "Generic Animal:" << std::endl;
genericAnimal.displayInfo();
genericAnimal.makeSound();
std::cout << "\nDog:" << std::endl;
myDog.displayInfo();
myDog.makeSound();
std::cout << "\nCat:" << std::endl;
myCat.displayInfo();
myCat.makeSound();
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Generic Animal:
Animal Name: Generic Animal
Some generic animal sound
Dog:
Animal Name: Buddy
Breed: Labrador
Woof! Woof!
Cat:
Animal Name: Whiskers
Color: Orange
Meow! Meow!
메서드 재정의에 대한 주요 사항:
- 재정의를 활성화하려면 기본 클래스에서
virtual키워드를 사용합니다. - 명시적으로 재정의하려면 파생 클래스에서
override키워드를 사용합니다. BaseClass::method()를 사용하여 기본 클래스 메서드를 호출할 수 있습니다.- 동일한 메서드에 대해 다른 구현을 허용합니다.
- 다형성 (polymorphic behavior) 을 가능하게 합니다.
접근 제어를 위한 Friend 함수 생성
이 단계에서는 C++ 의 프렌드 함수 (friend function) 에 대해 배우게 됩니다. 프렌드 함수는 외부 함수 또는 다른 클래스가 클래스의 private 및 protected 멤버에 접근할 수 있도록 허용합니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 프렌드 함수를 시연합니다.
#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
// Declare friend functions
friend void displayAccountDetails(const BankAccount& account);
friend class AccountManager;
public:
// Constructor
BankAccount(std::string name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
};
// Friend function that can access private members
void displayAccountDetails(const BankAccount& account) {
std::cout << "Account Holder: " << account.accountHolder << std::endl;
std::cout << "Current Balance: $" << account.balance << std::endl;
}
// Friend class that can access private members
class AccountManager {
public:
// Method that can access private members of BankAccount
void transferFunds(BankAccount& from, BankAccount& to, double amount) {
if (from.balance >= amount) {
from.balance -= amount;
to.balance += amount;
std::cout << "Transfer successful!" << std::endl;
} else {
std::cout << "Insufficient funds!" << std::endl;
}
}
};
int main() {
// Create bank accounts
BankAccount account1("Alice Johnson", 1000.0);
BankAccount account2("Bob Smith", 500.0);
// Use friend function to display account details
std::cout << "Account 1 Details:" << std::endl;
displayAccountDetails(account1);
std::cout << "\nAccount 2 Details:" << std::endl;
displayAccountDetails(account2);
// Use friend class to transfer funds
AccountManager manager;
std::cout << "\nTransferring $200 from Alice to Bob:" << std::endl;
manager.transferFunds(account1, account2, 200.0);
std::cout << "\nUpdated Account Details:" << std::endl;
displayAccountDetails(account1);
displayAccountDetails(account2);
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
Account 1 Details:
Account Holder: Alice Johnson
Current Balance: $1000
Account 2 Details:
Account Holder: Bob Smith
Current Balance: $500
Transferring $200 from Alice to Bob:
Transfer successful!
Updated Account Details:
Account Holder: Alice Johnson
Current Balance: $800
Account Holder: Bob Smith
Current Balance: $700
프렌드 함수에 대한 주요 사항:
friend키워드를 사용하여 선언합니다.- 클래스의 private 및 protected 멤버에 접근할 수 있습니다.
- 클래스 정의 내에서 선언됩니다.
- 개별 함수 또는 전체 클래스가 될 수 있습니다.
- 캡슐화 (encapsulation) 를 깨므로 신중하게 사용해야 합니다.
Static 멤버 및 메서드 사용
이 단계에서는 C++ 의 정적 멤버 (static member) 및 메서드 (method) 에 대해 배우게 됩니다. 정적 멤버와 메서드는 클래스의 모든 인스턴스에서 공유되며, 개별 객체가 아닌 클래스 자체에 속합니다.
WebIDE 에서 student.cpp 파일을 열고 코드를 수정하여 정적 멤버 및 메서드를 시연합니다.
#include <iostream>
#include <string>
class University {
private:
std::string name;
static int totalStudents; // Static member variable
static double totalTuition; // Another static member variable
public:
// Constructor
University(std::string universityName) : name(universityName) {}
// Method to add students
void addStudents(int count) {
totalStudents += count;
}
// Method to add tuition
void addTuition(double amount) {
totalTuition += amount;
}
// Static method to display total students
static void displayTotalStudents() {
std::cout << "Total Students Across All Universities: "
<< totalStudents << std::endl;
}
// Static method to display total tuition
static void displayTotalTuition() {
std::cout << "Total Tuition Collected: $"
<< totalTuition << std::endl;
}
// Static method to calculate average tuition
static double calculateAverageTuition() {
return (totalStudents > 0) ?
(totalTuition / totalStudents) : 0.0;
}
};
// Initialize static member variables outside the class
int University::totalStudents = 0;
double University::totalTuition = 0.0;
int main() {
// Create university objects
University harvard("Harvard University");
University mit("MIT");
University stanford("Stanford University");
// Add students and tuition
harvard.addStudents(5000);
harvard.addTuition(75000000.0);
mit.addStudents(4500);
mit.addTuition(65000000.0);
stanford.addStudents(4200);
stanford.addTuition(60000000.0);
// Call static methods directly on the class
std::cout << "University Statistics:" << std::endl;
University::displayTotalStudents();
University::displayTotalTuition();
// Calculate and display average tuition
std::cout << "Average Tuition per Student: $"
<< University::calculateAverageTuition() << std::endl;
return 0;
}
프로그램을 컴파일하고 실행합니다.
g++ student.cpp -o student
./student
예시 출력:
University Statistics:
Total Students Across All Universities: 13700
Total Tuition Collected: $2e+08
Average Tuition per Student: $14598.5
정적 멤버 및 메서드에 대한 주요 사항:
- 클래스의 모든 인스턴스에서 공유됩니다.
static키워드를 사용하여 선언됩니다.- 객체를 생성하지 않고도 접근할 수 있습니다.
- 개별 객체가 아닌 클래스에 속합니다.
- 클래스 전체 정보를 추적하는 데 유용합니다.
요약
이 랩에서는 객체 지향 프로그래밍 (object-oriented programming) 의 필수 개념인 private 데이터 멤버 (private data member) 를 사용하여 클래스를 정의하는 방법을 배웠습니다. Private 데이터 멤버는 객체의 내부 상태를 캡슐화하고 보호하는 데 도움이 됩니다. 또한 private 데이터 멤버에 대한 제어된 접근을 허용하는 public 멤버 함수 (public member function) 의 중요성에 대해서도 배웠습니다. 이는 데이터 무결성 (data integrity) 과 제어를 유지하는 데 도움이 됩니다. 추가적으로, 생성자 (constructor), 소멸자 (destructor), 접근 지정자 (access specifier), 상속 (inheritance), 메서드 오버라이딩 (method overriding), 프렌드 함수 (friend function), 정적 멤버 및 메서드 (static member and method) 의 사용법을 살펴보았습니다. 이 모든 것은 C++ 에서 객체 지향 프로그래밍의 기본적인 원리입니다.



