【发布时间】:2014-11-13 03:01:32
【问题描述】:
我来了
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 使用 Parking 的 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&。如果您认为它们是,您需要了解reference 是什么。 -
嗯,所以返回 *location;?那行得通,但我不确定。你也可以推荐一个好的网站,在那里我可以了解参考。谢谢
-
老实说,我没有理由首先看到动态分配该成员。
std::string已经动态管理其内容。只需创建成员std::string,在构造函数initializer list 中初始化它(和cost),并在你的getter 中初始化return location;。许多与 C++ 相关的好东西 can be read about here. -
@user2387963 那工作。你真正应该做的是让
location不是指针,然后只是return location;。 -
谢谢,但是当我删除指针时,我得到分段错误。代码更新
标签: c++ pointers reference return