C++ OOP 입문
Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 104개 중 5번째.
객체 지향 프로그래밍은 데이터와 동작을 함께 묶는 class로 코드를 구성합니다.
public 멤버가 있는 간단한 클래스
class Dog {
public:
std::string name;
int age;
std::string bark() {
return name + " says Woof!";
}
};객체 생성 및 사용
Dog dog;
dog.name = "Buddy";
dog.age = 3;
std::cout << dog.bark() << std::endl;출력:
Buddy says Woof!class는 구조를 정의합니다. 즉, 어떤 데이터를 보유하고 어떤 작업을 수행할 수 있는지를 정의합니다. 객체는 여러분이 생성하고 사용하는 특정 인스턴스입니다. public: 아래의 members는 어디에서나 액세스할 수 있습니다.
챌린지
쉬움Create Dog 클래스를 public members 및 methods와 함께 만드세요:
- public members:
name(string) 및age(int) bark(): returns"<name> says Woof!"info(): returns"<name> is <age> years old"
직접 해보기
#include <iostream>
#include "Dog.h"
int main() {
std::string name;
int age;
std::getline(std::cin, name);
std::cin >> age;
Dog dog;
dog.name = name;
dog.age = age;
std::cout << dog.bark() << std::endl;
std::cout << dog.info() << std::endl;
return 0;
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러