c++ 클래스

Hyunwoo Lee
5 min readMar 5, 2024

--

class 선언


#include <iostream>

class Car {
public:
Car() {}
double volume() { return height*width*length; }
void print() {
std::cout << height << " " << width << " " << length << std::endl; }

/* error 발생 => const 함수는 member 변수를 읽기만 가능.
void set(double h,double w, double l) const {
height = h;
width = w;
length = l;

}*/
double height, width, length;

};

int main()
{
Car car; // 클래스 선언을 stack에 하는 경우
car.height = car.width = car.length = 10; //.으로 변수와 함수에 접근
car.print();

Car* car_n= new Car(); //클래스 선언을 heap에 하는 경우
car_n->height = car_n->width = car_n->length = 11; //->로 변수와 함수에 접근
car_n->print();

return 0;
}

static variable , function

  • static variable : 같은 클래스끼리 공유되는 변수, 기본적으로 0으로 초기화됨
  • static function : static variable,다른 static member 함수 그리고 클래스밖의 다른 함수에 접근 가능.
class Box {
public:
static int objectCount; // static 변수는 같은 클래스끼리 공유됨.
double length, breadth, height;
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h;
objectCount++;
}
double Volume() {
return length * breadth * height;
}
/* => error 발생
static int getCount() {
return length;
}
*/
};
int Box::objectCount = 0;
void main(void) {
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
cout << "Total objects: " << Box::objectCount << endl;
}

Encapsulation : private, public 변수,함수

  • private는 클래스 밖에서 접근 불가, public은 가능.
  • Encapsulation이 필요한 이유? data consistency를 위해서 필요하다. 예를 들어 위 예제처럼 Volume()을 항상 계산하는 경우, 임의로 변수에 접근해서 width를 변경하게 되면 해당 값만 바뀌게 되고 volume은 재계산안된다
#include<iostream>
using namespace std;

class A {
public:
A() { value = 0;}
void f1(void) { value++; g1(); }
private:
void g1(void) { cout << "g1() was called" << endl; }
void g2(void) { cout << "g2() was called" << endl; }
int value;
public:
void f2(void) { g1(); g2(); }
};
int main(int argc, char** argv) {
A a;
a.f1();
a.f2();
//a.value = 1; // compile error
//a.g1(); // compile error
//a.g2(); // compile error
return 0;
}

protected? 상속받은 class에서도 접근가능한 변수.

private : 동일클래스에서만 접근 가능

protected : 동일클래스, 상속받은클래스

public : 동일클래스, 상속받은클래스, 외부

접근 지정자를 정하지 않으면 모든 변수는 private로 정의됨.

class Base
{
private: int a;
protected: int b;
public: int c;
};

class Derived : public Base
{
public:
void foo()
{
//a = 10; // error
b = 10; // ok
c = 10; // ok
}
};

int main()
{
Derived derv;
//derv.a = 10; // error
//derv.b = 10; // error
derv.c = 10; // ok
}

--

--