// C ์คํ์ผ ์ด๊ธฐํ
int num = 20;
int &ref = num;
// C++ ์คํ์ผ ์ด๊ธฐํ
int num(20);
int &ref(num);
์ ๋ฌธ์ฅ๋ค์ ๋ชจ๋ ๋์ผํ๋ค.
class SoSimple{
private:
int num1;
int num2;
public:
SoSimple(int n1, int n2) : num1(n1), num2(n2){}
void ShowSimpleData(){
cout << num1 << endl;
cout << num2 << endl;
}
}
int main(void){
SoSimple sim1(15,20);
SoSimple sim2 = sim1;
sim2.ShowSimpleData();
return 0;
}
๋์ ์ฐ์ฐ์ ์๋ฏธ์ฒ๋ผ ์ค์ ๋ฉค๋ฒ ๋ ๋ฉค๋ฒ์ ๋ณต์ฌ๊ฐ ์ผ์ด๋๋ค.
SoSimple sim2 = sim1;
SoSimple sim2(sim1);
์ ๋ ๋ฌธ์ฅ์ ๋์ผํ๋ค.
๐ SoSimple sim2(sim1) ํด์
SoSimpleํ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ผ.
๊ฐ์ฒด์ ์ด๋ฆ์ sim2
sim1์ ์ธ์๋ก ๋ฐ์ ์ ์๋ ์์ฑ์์ ํธ์ถ์ ํตํด์ ๊ฐ์ฒด์์ฑ์ ์๋ฃํ๋ค.
SoSimple(SoSimple ©) : num1(copy.num1), num2)(copy.num2) {
cout << "Called SoSimple(SoSimple ©)" << endl;
}
๐ SoSimple sim2=sim1์ ๋ฌต์์ ์ผ๋ก SoSimple sim2(sim1)์ผ๋ก ํด์๋๋ค.
๐ฉ ๋ํดํธ ๋ณต์ฌ ์์ฑ์
๋ณต์ฌ ์์ฑ์๋ฅผ ์ ์ํ์ง ์์ผ๋ฉด, ๋ฉค๋ฒ ๋ ๋ฉค๋ฒ์ ๋ณต์ฌ๋ฅผ ์งํํ๋ ๋ํดํธ ๋ณต์ฌ ์์ฑ์๊ฐ ์ฝ์ ๋๋ค.
SoSimple(const SoSimple ©) : num1(copy.num1), num2(copy.num2){}
๋ฌต์์ ํ๋ณํ์ ๋ง์ผ๋ ค๋ฉด explicit์ ํ์ฉํ๋ค.
explicit SoSimple(const SoSimple ©) : num1(copy.num1), num2(copy.num2){
// empty
}
Sosimple obj = 3 // ์ด๋ฌํ ํํ์ ๊ฐ์ฒด ์์ฑ ๋ถ๊ฐ๋ฅ
๐ฉ ๋ฌธ์ ์
๊ฐ์ฒด ์๋ฉธ์ ๋ฌธ์ ๊ฐ ๋๋ ๊ตฌ์กฐ (์์ ๋ณต์ฌ)
class Person{
private:
char * name;
int age;
public:
Person(char * myName, int myAge){
int len = strlen(myName) + 1;
name = new char[len];
strcpy(name, myName);
age = myAge;
}
~Person(){
delete []name;
}
}
๐ ๊น์ ๋ณต์ฌ๋ฅผ ์ํ ๋ณต์ฌ ์์ฑ์ ์ ์
Person(const Person ©) : age(copy.age){
name = new char[strlen(copy.name)+1];
strcpy(name, copy.name);
}
๐ฉ ๋ณต์ฌ ์์ฑ์ ํธ์ถ ์์
๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ํ ๋น๊ณผ ์ด๊ธฐํ๊ฐ ๋์์ ์ผ์ด๋๋ ์ํฉ
1. ๊ธฐ์กด์ ์์ฑ๋ ๊ฐ์ฒด๋ฅผ ์ด์ฉํด์ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์ด๊ธฐํํ๋ ๊ฒฝ์ฐ(์์ ๋ณด์ธ ๊ฒฝ์ฐ)
Person man1("Lee dong woo", 29);
Person man2 = man1; // ๋ณต์ฌ ์์ฑ์ ํธ์ถ
2. call-by-value ๋ฐฉ์์ ํจ์ํธ์ถ ๊ณผ์ ์์ ๊ฐ์ฒด๋ฅผ ์ธ์๋ก ์ ๋ฌํ๋ ๊ฒฝ์ฐ
3. ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋, ์ฐธ์กฐํ์ผ๋ก ๋ฐํํ์ง ์๋ ๊ฒฝ์ฐ
SoSImpel SimpleFuncObj(SoSimple ob){ // ์ธ์ ์ ๋ฌ ์ ์ ์ธ๊ณผ ๋์์ ์ด๊ธฐํ
...
return ob; // ๋ฐํ์ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ ํ ๋น๊ณผ ๋์์ ์ด๊ธฐํ
}
int main(void){
SoSimple obj;
SimpleFuncObj(obj);
}
๐ ๋ฐํํ ๋ ๋ง๋ค์ด์ง ๊ฐ์ฒด์ ์๋ฉธ ์์
class Temporary{
private:
int num;
public:
Temporary(int n) : num(n) {
cout << "create obj : " << num < endl;
}
~Temporary(){
cout << "destroy obj : " << num << endl;
}
void ShowTempInfo(){
cout << "My num is " << num << endl;
}
}
int main(void){
Temporary(100);
cout << "******** after make!" << endl << endl;
Tmporary(200).ShowTempInfo();
cout << "******** after make!" << endl << endl;
const Temporary &ref = Temporary(300); // ์ฐธ์กฐ๊ฐ์ด ๋ฐํ๋๋ฏ๋ก ์ฐธ์กฐ์๋ก ์ฐธ์กฐ ๊ฐ๋ฅ
cout << "******** end of main!" << endl << endl;
return 0;
}
const ์ฐธ์กฐ๊ฐ์ ๋ค ๋๋๊ณ ์๋ฉธ๋๋ค.
'๐ฉโ๐ป ํ๋ก๊ทธ๋๋ฐ > ๐ C++' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++] ์์๊ณผ ๋คํ์ฑ | ๊ฐ์ํจ์(virtual function) | ์ฐธ์กฐ์ (1) | 2024.04.26 |
---|---|
[C++] ์์ (0) | 2024.04.23 |
[C++] ํด๋์ค์ ๋ฐฐ์ด, this ํฌ์ธํฐ (0) | 2024.04.18 |
[C++] ์์ฑ์์ ์๋ฉธ์ (0) | 2024.04.18 |
[C++] ์ ๋ณด ์๋ | ์บก์ํ (0) | 2024.04.17 |