[C++] λ³΅μ¬ μμ±μ | κΉμ 볡μ¬μ μμ 볡μ¬
// 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 μ°Έμ‘°κ°μ λ€ λλκ³ μλ©Έλλ€.