//Animal.h
class Animal
{
//...
public:
Animal(int age);
inline int GetAge() const;//인라인 함수 정의
}
int Animal::GetAge() const
{
return mAge;//함수단에서 public private 권한체크는 함.
}
//Main.cpp
Cat* myCat = new Cat(2, "Coco");
int age = myCat->GetAge();//이 코드를
int age = myCat.mAge;//이렇게 컴파일러가 바꿔줌
//매크로와 매우 비슷한 개념
#define SQUARE(x) (x)*(x)
int main()
{
int result = SQUARE(3)
// -> int result = (3)*(3); 코드로 전처리기가 바꿔줌
}
매크로 대신 인라인함수를 쓰는 이유
inline 함수 사용시 주의점
#pragma once
namespace samples
{
class Vector
{
public:
Vector();
Vector(int x, int y);
inline int GetX() const;//getter setter 인라인하기좋음.
inline void SetX(int x);
inline int GetY() const;
inline void SetY(int y);
inline bool IsEqual(const Vector& v) const;
inline Vector Multiply(const Vector& v) const;
inline Vector Multiply(int multiplier) const;
inline void Scale(const Vector& v);
inline void Scale(int multiplier);
//IsEqual, Multiply Scale 등 간단한 수학적인 함수들
//인라인하기 좋은 함수들임.
private:
int mX;
int mY;
};
//함수 정의부는 Inline 키워드 안붙여도됨.
//함수 정의 역시 컴파일러가 알아야 하기때문에 헤더파일에 있음.
int Vector::GetX() const
{
return mX;
}
void Vector::SetX(int x)
{
mX = x;
}
void Vector::SetY(int y)
{
mY = y;
}
int Vector::GetY() const
{
return mY;
}
bool Vector::IsEqual(const Vector& v) const
{
return (mX == v.mX && mY == v.mY);
}
Vector Vector::Multiply(const Vector& v) const
{
Vector result(mX * v.GetX(), mY * v.GetY());
return result;
}
Vector Vector::Multiply(int multiplier) const
{
Vector result(mX * multiplier, mY * multiplier);
return result;
}
void Vector::Scale(const Vector& v)
{
mX *= v.mX;
mY *= v.mY;
}
void Vector::Scale(int multiplier)
{
mX *= multiplier;
mY *= multiplier;
}
}
//ExternTest.h
extern int globalValue;
void IncreaseValue();
//Main.c
#include "ExternTest.h"
int main()
{
printf("%d", globalValue);
//...
}
//StaticTest.h
extern int globalValue;
void IncreaseValue();
//StaticTest.cpp
#include "StaticTest.h"
static int globalValue = 2;
void IncreaseValue()
{
globalValue++;
}
//Main.cpp
#include "StaticTest.h"
int main()
{
//링커 에러
printf("%d", globalValue);
return 0;
}
정적멤버함수 예시
#pragma once
namespace samples
{
class Math
{
public:
static int Ceil(float value);
static int Floor(float value);
static float Power(float value, float power);
static int Round(float value);
static float Square(float value);
private:
Math() {};
//누군가 Math 개체를 만들지 못하게 하기 위해서 private에정의하면
new Math 하더라도 컴파일에러가남
};
}
#include <iostream>
#include "Math.h"
namespace samples
{
int Math::Ceil(float value)
{//static_cast float to int 는 소수점을 버림.
int intValue = static_cast<int>(value);
if (value == static_cast<float>(intValue))
{
return intValue;
}
return intValue + 1;
}
int Math::Floor(float value)
{
return static_cast<int>(value);
}
float Math::Power(float value, float power)
{
return pow(value, power);
}
int Math::Round(float value)
{
return static_cast<int>(value + 0.5f);
}
float Math::Square(float value)
{
return value * value;
}
}