내가문자열 개체에 대한 참조를 반환하는 중 오류 : ç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.cpp 및 MAIN.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);
'std :: string **'은'std :: string '이 아닙니다. 그들이 있다고 생각한다면, * 참조가 무엇인지를 알아야합니다. – WhozCraig
음, 따라서 * location; 그건 작동하지만 확실하지 않았습니다. 또한 내가 참조 할 수있는 좋은 웹 사이트를 추천 할 수 있습니다. 덕분에 –
솔직히 말해서, 먼저 동적으로 할당 할 수있는 이유는 없습니다. 'std :: string'는 이미 내용을 동적으로 관리합니다. 그냥'std :: string' 멤버를 만들고 생성자 * 초기화 목록에서 초기화하고 ('cost'), getter에서'return location;'을 만듭니다. 많은 좋은 것들이 C++ 관련 [** 여기에서 읽을 수 있습니다 **] (http://en.cppreference.com/w/cpp/language). – WhozCraig