2011-02-17 5 views
1

만들어 채우기, I는 회원에게 (테스트 용 번호,이 경우) Array 문자열 배열에서 가져온 이름을 사용하여 클래스 bookName 오의 객체를 초기화하는 for 루프를 사용하는 것을 시도하고있다 . 그러나문제가 동적으로 아래의 코드에서 배열

#include <iostream> 
#include <string> 
using namespace std; 

class book 
{ 
private: 
    string Name; 
public: 
    book(); 
    book(string&); 
}; 

book :: book() 
{} 

book :: book(string& temp) 
{ 
    Name = temp; 
} 

int main() 
{ 
    string Array[] = {"1", "2", "3", "4", "5"}; 
    book *BookList = new book[5]; 
    for (int count = 0; count < 5; count ++) 
    { 
     BookList[count] = new book(Array[count]); 
    } 
    return 0; 
} 

, 나는 코드를 컴파일 할 때마다, 나는 다음과 같은 오류 얻을 :

main.cpp: In function ‘int main()’: 
main.cpp:28: error: no match for ‘operator=’ in ‘*(BookList + ((unsigned int)(((unsigned int)count) * 4u))) = (operator new(4u), (<statement>, ((book*)<anonymous>)))’ 
main.cpp:6: note: candidates are: book& book::operator=(const book&) 

내 의도 만하면 알려진 것입니다 private 멤버 값을 사용하여 객체의 배열을 생성하는 것입니다 루프는 관련 데이터를 수집합니다. answer #2 to a question I asked here previously에 제공된 조언을 따르고 있습니다.

+0

'BookList' 배열을 만들고'book' 객체로 초기화하려고하는 것 같습니다. – Argote

+0

멤버 변수'Name'을 초기화하기 위해 별도의 setter 메소드를 작성해야합니다. – Mahesh

답변

5
book *BookList = new book[5]; 

BookList 다섯 book 객체들의 어레이이다.

BookList[count] = new book(Array[count]); 

당신은 book 객체에 다섯 포인터의 배열처럼 BookList를 사용하려고합니다.

BookList[count]count 번째 book되면, count 번째 book 포인터 아니다.

std::vector과 같은 표준 라이브러리 컨테이너 중 하나를 사용 해본 적이 있습니까? 당신은 그들이 무엇인지 알 때까지 book의를 삽입하지 않으려면, 당신은 초기합니다 ((5) 초기화를 제거하여) 0의 크기와 push_back 또는 같은 insert 책을 만들 수 있습니다

std::vector<book> BookList(5); 

또는, 필요하다.

0
BookList[count] = new book(Array[count]); 

당신은 기본적으로하고 있습니다 : book = book* 서로 다른 종류이기 때문에 분명히 작동하지 않을 것이다. 당신은 new 키워드를 삭제할 수 있습니다 :

BookList[count] = book(Array[count]); 

이 임시 book 객체를 생성하고, BookList의 책 중 하나에 할당합니다.

관련 문제