2014-09-18 1 views
2

내가문자열 개체에 대한 참조를 반환하는 중 오류 : çconst string 유형의 참조 초기화가 유효하지 않습니다. C++

error: invalid initialization of reference of type âconst string& {aka const std::basic_string<char>&}â from expression of type âstd::string* const {aka std::basic_string<char>* const}â 

을 얻고 나는 총 4 개 파일, parking.h, parking.cpp, printPark.cppMAIN.CPP을

이가되어 있습니다 내가 뭘하는지,

//parking.h 
Class Parking { 
    string location; 
    int cost; 

    public: 
    void set(const std::string &loc, int num); 
    const std::string& getLocName() const(); 

} 

.

//parking.cpp 
void Parking::set(const std::string &loc, int num) { 
    //location = new string; 
    location = loc; 

    cost = num; 
} 

// needs to return a reference to a string object 
const std::string& Parking::getLocName() const() { 

    return location; 
} 

내 printPark.cpp은 화면 인쇄, 주차의 getLocName()를 사용합니다. 그것은 주차 객체에 대한 메모리를 동적으로 할당하고 파일로부터의 사용자 입력을 문자열 변수로 설정합니다.

//printPark.cpp 

//if parking info is in parking.dat load it. 

string a, b; 
int num =5; 

ifstream f(filename); 
getline(f, a, '\n'); 
getline(f, b, '\n'); 

parking = new Parking[2]; 

parking[0].set(a,num); 
parking[1].set(b, num); 
+1

'std :: string **'은'std :: string '이 아닙니다. 그들이 있다고 생각한다면, * 참조가 무엇인지를 알아야합니다. – WhozCraig

+0

음, 따라서 * location; 그건 작동하지만 확실하지 않았습니다. 또한 내가 참조 할 수있는 좋은 웹 사이트를 추천 할 수 있습니다. 덕분에 –

+1

솔직히 말해서, 먼저 동적으로 할당 할 수있는 이유는 없습니다. 'std :: string'는 이미 내용을 동적으로 관리합니다. 그냥'std :: string' 멤버를 만들고 생성자 * 초기화 목록에서 초기화하고 ('cost'), getter에서'return location;'을 만듭니다. 많은 좋은 것들이 C++ 관련 [** 여기에서 읽을 수 있습니다 **] (http://en.cppreference.com/w/cpp/language). – WhozCraig

답변

1

당신은 주소 혼란 참조있어 (그들은 같은 아니에요, &의 위치는 중요하다).

솔직히 말해서 std::string은 동적으로 콘텐츠를 이미 관리하므로 동적으로 할당해야 할 필요는 없습니다.

//parking.h 
class Parking 
{ 
    std::string location; 
    int cost; 

public: 
    // default constructor 
    Parking() : cost() 
    { 
    } 

    // parameterized constructor 
    Parking(const std::string& loc, int num) 
     : location(loc), cost(num) 
    { 
    } 

    void set(const std::string &loc, int num) 
    { 
     location = loc; 
     cost = num 
    } 

    const std::string& getLocName() const 
    { 
     return location; 
    } 
}; 

이렇게하면 Parking도 복사 가능합니다. 대입 할 수 있으며, 대입 할 수있는 사용자 정의 복사 생성자, 대입 연산자 및 소멸자를 Rule of Three에 따르지 않아도됩니다.

+0

으로 업데이트되면 seg fault가 발생합니다> location = loc; –

+0

@ user2387963 원래 질문과는 완전히 관련이 없습니다. 그것은 발신자 쪽에서 문제가 될 것입니다. 이 코드를 (신중하게) 다시보십시오. 귀하의 코드가 지금 당장 보이므로, 당신의 패스가 문제가 될 가능성이 있습니다. (어쩌면 당신이 암시 적으로'char *'를 전달할 것입니다. – WhozCraig

+0

그래, 나도 알아,하지만 난 세그 잘못되고 있었어. 그래서 그것을 포인터로 만들었습니다. 발신자에게는 주차장이 있습니다. parking.set (loc, number) loc은 문자열입니다. –

관련 문제