编译器无法识别其他方法中的重载方法

时间:2020-09-01 12:24:32

标签: c++ string overloading

我有两个类:“ Station”具有返回字符串的方法getName()和“ Profit”,其具有重载方法sellAt(string stName),sellAt(Station st)。为了避免重复的代码,我在sellAt(string stName)中调用了sellAt(string stName),但是在某些情况下(请参见下面的代码示例),编译器给出了一个错误:“没有重载函数的实例” Profit :: SellAt”与参数列表匹配。参数类型为:(std :: string)”。是错误还是我错过了什么?

Station.h

#pragma once
#include <string>

using namespace std;

class Station
{
private:
    string sName;
public:
    Station(string name);
    string getName();
};

Station.cpp

#include "Station.h"

Station::Station(string name)
    :sName(name)
{}

string Station::getName()
{
    return sName;
}

Profit.h

#pragma once
#include "Station.h"
#include <string>

class Profit
{
public:
    double SellAt(string& stName);
    double SellAt(Station& st);
};

Profit.cpp

#include "Profit.h"

double Profit::SellAt(const string& stName)
{
    // do stuff
}

// Works as expected
double Profit::SellAt(Station& st)
{
    string stName = st.getName();
    return SellAt(stName);
}

// Compile error
double Profit::SellAt(Station& st)
{
    return SellAt(st.getName());
}

// Compile error
double Profit::SellAt(Station& st)
{
    double result = SellAt(st.getName());
    return result;
}

1 个答案:

答案 0 :(得分:1)

Yksisarvinen在原始问题下方的评论中回答:

st.getName()是临时的。您不能将非常量引用绑定到临时表。我想您不应该在Profit :: SellAt()中修改stName,所以将参数类型更改为const std :: string&。

感谢您的帮助!

相关问题