다음 클래스에서 계약자는 주 함수에서 문자열과 int ("Jan", 24)를 가져와야합니다. 하지만 1과 같은 다른 임의의 정수가 나이로 인쇄되기 때문에 정수가 전달되면 잘못된 것이있는 것 같습니다.동적 메모리 할당 후 생성자에 정수 전달
#include <iostream>
#include <string>
using namespace std;
class Human{
private:
string *name;
int *age;
public:
Human(string iname, int iage){
name = new string;
age = new int;
name = &iname;
age = &iage;
}
void display(){
cout << "Hi I am "<<*name<<" and i am "<<*age<<" years old"<<endl;}
~Human(){
delete name;
delete age;
cout << "all memories are released"<<endl;
}
};
int main()
{
Human *Jan = new Human("Jan",24);
Jan->display();
delete Jan;
return 0;
}
출력은 다음과 같으며 24 대신 나이가 인쇄됩니다. 내가 내 생성자를 변경하는 경우
Hi I am Jan and I am 1 years old
untitled(5417,0x7fff8ed19340) malloc: *** error for object
0x7ffeed4c19b8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
내가 알고있는 (나이 = 24) 예상대로 작동하지만 위의 코드가 작동 및 인쇄 나이 = 1하지 않는 이유를 알고 관심 다음과 같습니다.
Human(//the same parameter as before)
{
//the same memory allocation
*name = iname;
*age = iage;
}
왜 두 번째 질문은 왜곡자가 첫 번째 코드에서 공개되지 않는 이유입니까?
C++이며 Resource Acquisition Is Initialization 또는 RAII를 알고 있어야합니다. – icaptan