【问题标题】:Returning a reference to a string object, error: invalid initialization of reference of type âconst string&. c++返回对字符串对象的引用,错误:“const string&”类型的引用初始化无效。 C++
【发布时间】: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 和 ma​​in.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&amp;。如果您认为它们是,您需要了解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


【解决方案1】:

您将引用与地址混淆(它们不一样;&amp; 的位置很重要)。

说实话,您可能一开始就不需要动态分配该成员,因为 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(不管怎样,您可能都想阅读它,因为它很重要)。

【讨论】:

  • 调试后,我在 >location = loc; 处出现段错误
  • @user2387963 与原始问题完全无关。这将是 caller 方面的问题,而不是这个。再次(仔细)查看这段代码。您的代码现在看起来,因此您传递的 source 字符串可能是问题所在(也许您隐式传递了不确定的 char*)。
  • 是的,我知道,但我遇到了段错误。所以使它成为一个指针。来电者有停车位; park.set(loc , number) loc 是一个字符串。
  • 然后也从调用方发布代码(在问题中),并包括在传递给之前如何创建源字符串loc 的机制set(),因为我觉得这很重要。并认真考虑提出一个不同的问题,同样,该问题与这个问题无关。此答案中的代码(现在您在上面的帖子)是正确的。当您说“我的 main 为停车对象动态分配内存......”时,我祈祷您没有使用 malloc。你应该使用new。所以把代码贴在main.cpp
  • 对不起,我的主要是 printPark.cpp。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多