nullptr
#include<iostream>
int main() {
int* p = nullptr;
if (p)
std::cout << *p << std::endl;
p = new int(5);
if (p)
std::cout << *p << std::endl;
p = nullptr;
if (p)
std::cout << *p << std::endl;
std::cout << "end" << std::endl;
}
// -> 5 end
// p=nullptr 없을 시 -> 비정상적으로 프로그램이 종료됨 p는 아무것도 없는 주소를 가리키기때
this pointer
#include<iostream>
class Point {
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
Point *Set(int x, int y) // this 포인터를 반환
{
*this = { x,y };
return this;
}
void Inc() {
x++;
y++;
}
void Print() const {
std::cout << x << ", " << y << std::endl;
}
};
int main()
{
Point p(1, 2);
p.Print();
p.Set(3, 4);
p.Print();
p.Set(5, 6)->Inc();
p.Print();
}
Abstract class
- 순수가상함수 하나 가지면됨
- 순수가상함수 : virtual function 프로토타입만 지정해줌
#include <iostream>
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle" << std::endl;
}
};
int main() {
Circle c;
c.draw();
return 0;
}
Copy constructor
- classname (const classname &)
#include<iostream>
class Ex {
int x;
public:
Ex(int x = 0) : x(x) {}
Ex(const Ex& e) :x(e.x) {} //copy constructor 호출
void print() const {
std::cout << x << std::endl;
}
};
Ex Copy(Ex e) {
e.print();
return e;
}
int main()
{
Ex e1(100);
Ex e2(e1);
e1.print();
e2.print();
Copy(e1).print();
}
Copy Assignment operator
#include<iostream>
class Ex {
int x;
public:
Ex(int x = 0) : x(x) {}
Ex& operator = (const Ex& e) {
x = e.x;
return *this;
}
void print() const
{
std::cout << x << std::endl;
}
};
int main()
{
Ex e1(100), e2;
e2 = e1;
e2.print();
}
Rvalue References