2. Cpp์ ๋ ํนํ ์ฌ์ฉ๋ฒ
by JiwonDev1. ์ฐ์์ ์ธ ๊ฐ ์ถ๋ ฅํ๊ธฐ
#include <iostream> using namespace std; int main() { int A[5]={0,}; for(int i=0; i<5; i++) // for cout << A[i] << " "; cout << "\n"; for(int x:A) // for-each cout << x << " "; return 0; }
2. Reference ๋ณ์
call-by-reference ๋ฅผ ๋ณ์์ ์ ์ฉํ ๊ฒ์ผ๋ก ๊ฐ์ ๋ณต์ฌํ์ง ์๊ณ ์ฃผ์๊ฐ ์์ฒด๋ฅผ ์ ๋ฌํ๋ค.
์ฃผ์๋ฅผ ๋ํ๋ด๋ & ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ๋ค.
#include <iostream> using namespace std; int main() { int a = 10; int &r = a; // ๋ ํผ๋ฐ์ค ๋ณ์ r r++; cout << r << endl; // 11 cout << a << endl; // 11 }
์ฐธ๊ณ ๋ก a = &r ์ ํ๊ฒ๋๋ฉด r์ ์ฃผ์๊ฐ์ด ๋ค์ด๊ฐ๊ฒ ๋๋ค. (๋ ํผ๋ฐ์ค ๋ณ์๊ฐ ์๋๋ค.)
2-1 ํฌ์ธํฐ ๋ณ์์ ๋ ํผ๋ฐ์ค ๋ณ์
ํฌ์ธํฐ ๋ณ์๋ ํฌ์ธํฐ ๊ฐ์ ๋ด๋ 4๋นํธ ์๋ฃํ์ด๊ณ
๋ ํผ๋ฐ์ค ๋ณ์๋ ์ต์ ํ. ์ฆ ๋๊ฐ์ ๋ด์ฉ์ ๋ณ์์ด๋ฆ ํ๋ ๋ ๋๊ณ ์ฌ์ฉํ๋ค๊ณ ์๊ฐํ๋ฉด ๋๋ค.
๋ ํผ๋ฐ์ค ๋ณ์์ ์ฅ์ ์ ์ธ๋ชจ์๋ ๋ฉ๋ชจ๋ฆฌ ๋ญ๋น๋ฅผ ์ค์ผ ์ ์๋ค๋ ์ .
#include <iostream> using namespace std; void swap_by_reference(int &a, int &b){ // ๋ณ์ ์์ฒด๋ฅผ ์ ๋ฌ๋ฐ๋๋ค. int temp; temp = a; a = b; b = temp; } void swap_by_pointer(int *a, int *b){ // ์ฃผ์๊ฐ์ ์ ๋ฌ ๋ฐ๋๋ค. int temp; temp = *a; // ํฌ์ธํฐ ๋ณ์์ ์ฌ์ฉ๋ฒ *a = *b; // *๋ ํด๋น ์ฃผ์๊ฐ ๊ฐ๋ฅดํค๋ ๊ฐ. *b = temp; } int main() { int a=10, b=20; swap_by_reference(a, b); cout << a << b << endl; swap_by_pointer(&a, &b); cout << a << b << endl; }
3. Const (์์ํ)

4. Struct (๊ตฌ์กฐ์ฒด)
๊ฐ๋จํ ๊ตฌ์กฐ๋ ๊ตฌ์กฐ์ฒด๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ๋ค๊ณ ๋ ํ๋๋ฐ
์์งํ๊ฒ ๊ตณ์ด ์จ์ผํ๋ ์ด์ ๋ ๋ชจ๋ฅด๊ฒ ๋ค. C์ธ์ด์ ์์ด์ ํธํ์ฑ ๋๋ฌธ์ ๋จ์๊ฒ ์๋๊น?
์ฐธ๊ณ ๋ก ์ ๊ทผ์ง์ ์๊ฐ public์ด๋ผ๋ ๊ฑธ ์ ์ธํ๋ฉด Class์ ๋น์ทํ๋ค.
#include <iostream> using namespace std; struct Rectangle { int length; // ๋ช
์ํ์ง์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ์ public int breadth; // ๊ทผ๋ฐ ์์งํ struct๋ฅผ ์ ์ฐ๋์ง๋ ์ ๋ชจ๋ฅด๊ฒ ๋ค. }; // ์ธ๋ฏธ์ฝ๋ก ์ด ๋ถ๋ค? int main() { struct Rectangle r = {10,5}; struct Rectangle *p = &r; /* p = ๋์ ํ ๋น์ ํ ๊ฒฝ์ฐ p = (struct Rectangle*) malloc( sizeof(struct Rectangle) ); */ r.length = 15; cout << r.length << endl; // r.length = 15 (*p).length = 25; cout << r.length << endl; // r.length == 25 p->length=30; cout << r.length << endl; // r.length == 30 }
5. Class
ํด๋์ค๋ ๋ค์์ฅ์ ์ถ๊ฐ๋ก ์ค๋ช ํ๊ฒ ๋ค. ๊ฐ๋จํ๊ฒ ์ฝ๋๋ง ๋ณด๊ณ ๊ฐ์
#include <iostream> #include <stdio.h> using namespace std; class Rectangle { private: // ๋ช
์ํ์ง์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ์ private์
๋๋ค. int length; int breadth; public: Rectangle() { // ์์ฑ์ length = 0; breadth = 0; } Rectangle(int l, int b) { // ์์ฑ์ ์ค๋ฒ๋ผ์ด๋ฉ length = l; breadth = b; } ~Rectangle(){ // ์๋ฉธ์ cout << "Destructor"; } int area(){ // ๋๋น return length * breadth; } int perimeter(){ // ๋๋ return 2*(length+breadth); } void setLength(int l){ // setter length=l; } void setBreadth(int b){ breadth=b; } int getLength(){ // getter return length; } int getBreadth(){ return breadth; } }; // cpp class๋ ์ธ๋ฏธ์ฝ๋ก ์ ๋ต๋๋ค ใ
ใ
; int main(){ Rectangle r(10,5); cout << "Area " << r.area() << endl; cout << "Perimeter " << r.perimeter() << endl; }
๋ธ๋ก๊ทธ์ ์ ๋ณด
JiwonDev
JiwonDev