返回对字符串对象的引用,错误:类型为 â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.hparking.cppprintPark.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使用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已经动态管理其内容了。

//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具有可复制性。和可赋值的,而不必编写自定义的复制构造函数、赋值运算符和析构函数来遵守三规则(不管怎样,您可能都想阅读它,因为它很重要)。

相关内容

最新更新