typedef struct _node {
string str;
} node;
int main() {
node* a = (node*)malloc(sizeof(node) * 5);
for(int i = 0; i < 5; i++) {
a[i].str = "123";
cout << a[i].str << endl;
}
return 0;
}
이게 실행이 안되는데..
a[i].str = "123";
여기서 자꾸 에러가 나는데
이유를 아는 사람?
어떻게 고쳐야함?? ㅜ
str은 프라이버트 메서드입니다.
코로모/ 그럼 어떻게 고쳐야하는거에요??
C언어로 고치세요
char배열로요? 그 수밖에 없나..
아니면 public: 추가하시거나 str을 초기화하셈
코드가 엄청 길고 중간중간에 구조체 내용을 계쏙 바꿔야해서요
public은 어디다가 추가하면 되는거에요?
string str; 줄 위에요 {와 string str; 사이에
아하! 감사합니다!!!
복받으실꺼에요!!
죄송한데, struct는 모든 멤버가 public인 특별한 class입니다. 문제는 접근한정자가 아니예요...
#include <iostream>#include <malloc.h>using namespace std;struct node { string str;};int main(void){ struct node *node = new struct node[5]; for (int i=0; i<5; i++) { node[i].str = *new string("123"); cout << node[i].str << endl; } return 0;}
malloc()으로 메모리를 할당하게 되면 생성자가 호출되지 않기 때문에 오작동으로 이어질 수 있어요. new로 바꿔주면 잘 실행되요~ 이 외에도 틀린 부분 수정했으니 참고하세요.
예전에 struct로 템플릿구현했을 때 public을 죄다 써놨었는데 아무 기능을 하지 않는 거였네요;;