반응형
구조체
- 기본이 public
#include <iostream>
using namespace std;
struct Student {
private:
string name;
public:
Student(string name) : name(name) {}
string getName() {
return name;
}
};
int main() {
Student student("ABC");
cout << student.getName() << endl;
return 0;
}
클래스
- 기본이 private
#include <iostream>
using namespace std;
class Student {
private:
string name;
public:
Student(string name) : name(name) {}
string getName() {
return name;
}
};
int main() {
Student student1("ABC-1");
Student student2 = Student("ABC-2");
cout << student1.getName() << endl;
cout << student2.getName() << endl;
return 0;
}
생성자, 소멸자
#include <iostream>
using namespace std;
class Student {
public:
Student() {
cout << "생성자" << endl;
}
~Student() {
cout << "소멸자" << endl;
}
};
int main() {
Student student;
cout << "main 함수 시작" << endl;
cout << "main 함수 종료" << endl;
return 0;
}
클래스 정적 멤버
#include <iostream>
using namespace std;
class Calculator {
public:
static int add(int a, int b) {
return a + b;
}
};
int main() {
int result = Calculator::add(2, 3);
cout << result << endl;
return 0;
}
연산자 오버로딩
#include <iostream>
using namespace std;
class Vector2 {
private:
float x;
float y;
public:
Vector2(float x, float y) : x(x), y(y) {}
Vector2 operator+(Vector2 other) {
return Vector2(x + other.x, y + other.y);
}
float getX() {
return x;
}
float getY() {
return y;
}
};
int main() {
Vector2 a(2, 3);
Vector2 b(-1, 4);
Vector2 c1 = a.operator+(b);
Vector2 c2 = a + b;
cout << c1.getX() << ", " << c1.getY() << endl;
cout << c2.getX() << ", " << c2.getY() << endl;
return 0;
}
동적할당
#include <iostream>
using namespace std;
class Student {
private:
string name;
public:
Student(string name) : name(name) {}
string getName() {
return name;
}
};
int main() {
Student *student = new Student("ABC-3");
cout << student->getName() << endl;
delete student;
return 0;
}
반응형
'Development > C, C++' 카테고리의 다른 글
[C++] 동적할당 (0) | 2019.04.11 |
---|---|
[C++] 문법 (0) | 2019.04.04 |
[C] 유용한 함수들 (0) | 2019.04.04 |
[C] 파일 입출력 (0) | 2019.04.04 |
[C] 상수 (0) | 2019.04.04 |