#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Sample {
char* name;
public:
static int count;
Sample() {
cout << "생성자 호출" << this << endl;
name = NULL;
count++;
}
Sample(const char* name ) {
cout << "const char* name 생성자 호출 : " << this << endl;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
count++;
}
~Sample() {
cout << "소멸자 호출 : " << this << endl;
delete[] name;
}
Sample(const Sample& a) {
cout << "복사 생성자 호출 : " << this << endl;
name = new char[strlen(a.name) + 1];
strcpy(name, a.name);
count++;
}
Sample& operator=(const Sample& a) {
delete[] name;
cout << "대입연산자 호출 "<< this << endl;
name = new char[strlen(a.name) + 1];
strcpy(name, a.name);
return *this;
}
char* printName() { return name; }
int printCount() { return count; }
int printCount() { return count; }
};
int Sample::count = 0;
int main() {
Sample a("Sample");
Sample b(a);
Sample c;
c = a;
cout << a.printName() << endl;
cout << b.printName() << endl;
cout << c.printName() << endl;
cout << "객체의 수 : " << a.printCount() << endl;
}
Sample() {
cout << "생성자 호출" << this << endl;
name = NULL;
count++;
}
Sample(const char* name ) {
cout << "const char* name 생성자 호출 : " << this << endl;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
count++;
}
위의 코드를 디폴트 매개변수를 이용해서 하나로 묶어서 처리하려고 아래와 같이 바꿨음. ㅇㅇ
Sample(const char* name = NULL ) {
if(name == NULL) cout << "생성자 호출" << this << endl;
else cout << "const char* name 생성자 호출 : " << this << endl;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
count++;
}
그런데 생성자 호출까지만 뜨고 그 아래는 실행조차 안되고 종료됨.
내가 봤을 땐 널인 name을 삭제해서 인듯 저기서 예외사항으로 if(name) 또는 if(name != nullptr) delete [] name; 해주면 될듯한데?
형들 푸바오아이형이 해결해줬어 신경써준 형들 다 고마워