[C++] C++ Class

JAsmine_log·2024년 5월 18일

C++

Class

Class는 데이터구조의 확장된 형태이다. 데이터구조처럼 data(data member)와 function(function member)을 포함한다. 즉, 데이터와 함수를 선언하여 사용한다.

Tip
:: 는 범위 지정 연산자(scope resolution operator)로, 클래스의 정적 멤버나 네임스페이스의 멤버에 접근에 접근할 때 사용할 수 있다.
$ClassName ::
%NameSpaceNmae ::

구조

아래는 class의 구조이다.

class class_name {
  access_specifier_1:
    member1;
  access_specifier_2:
    member2;
  ...
} object_names;

상속 관계

public = 어디서든 접근이 가능
protected = 상속관계일 때 접근이 가능
private = 해당 클래스에서만 접근이 가능

부모 클래스 상속public 상속protected 상속private 상속
pulbic 멤버publicprotectedprivate
protected 멤버publicprotectedprivate
private 멤버접근 불가접근 불가접근 불가
접근 불가 멤버접근 불가접근 불가접근 불가

예시

아래 코드는 Rectagle Class를 구현한 예시이다.
class를 정으의하고 Rectangle 객체를 생성하여 각각 values를 설정할 수 있다.
여기서, set_values는 객체의 width와 height로 지정되고, area를 계산할 때 사용한다.

// classes example
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {
  width = x;
  height = y;
}

int main () {
  Rectangle rect;
  Rectangle rectb;
  rect.set_values (3,4);
  rectb.set_values (5,6);
  cout << "area: " << rect.area();
  cout << "area: " << rectb.area();

  return 0;
}
>> 12
   30

Reference

[1] https://cplusplus.com/doc/tutorial/

profile
Everyday Research & Development

0개의 댓글