类中的功能定义需要与其他类中的功能相同:编译错误

问题描述 投票:1回答:1

我有一个枚举类“ Suit”,并定义了一个函数“ string to_string(Suit e)”

[在另一类“卡片”中,我有一个成员变量“ my_Suit”和一个成员函数“ to_string”。该函数使用“ my_Suit”作为参数调用函数“ to_string”。

[在编译时,我得到一个错误,即编译器(g ++)正在寻找函数“ Card :: to_string(Suit&)”,但该函数不存在(不在提到的范围“ Card ::”之内)。

错误状态:

错误:没有匹配功能可调用'Card :: to_string(Suit&)'

候选人:std :: __ cxx11 :: string Card :: to_string()

我如何向编译器表明他必须搜索在类外部定义的函数?

这是一段在编译时给出错误的代码。实际上,该代码在几个头文件和源文件之间划分,但错误保持不变。

#include <iostream>

/********************  enum class Suit  ********************/

enum class Suit
{
    Clubs, Spades, Hearts, Diamonds
};

std::string to_string(Suit e) 
{
    return ("calling 'to_string' function with Suit as parameter");
}

/********************  clas Card  ********************/

class Card
{

    private:
        Suit m_Suit;
    public:
        Card()  { m_Suit = Suit::Clubs; }

        std::string to_string() 
        {
            return ( to_string(m_Suit) );
        }
};

int main()
{
    std::cout << "Hello world!\n";
    return (0);
}
c++ compiler-errors
1个回答
0
投票

使用限定名称。例如

    std::string to_string() 
    {
        return ( ::to_string(m_Suit) );
    }

0
投票

因为OP已经怀疑这是范围问题。

class Card有其自己的范围并提供成员Card::to_string()

内部成员函数首先尝试在类范围内解析所有符号,如果失败则将其解析到外部范围。

在这种情况下,名称解析没有失败,但是提供了一个候选。

不幸的是,名称解析一旦找到候选者便停止,在OP中是错误的名称。

因此,需要一些显式帮助–范围运算符(::)。

固定的Card::to_string()

        std::string to_string() 
        {
            return ::to_string(m_Suit);
        }

OP的固定样本:

#include <iostream>

/********************  enum class Suit  ********************/

enum class Suit
{
    Clubs, Spades, Hearts, Diamonds
};

std::string to_string(Suit e) 
{
    return ("calling 'to_string' function with Suit as parameter");
}

/********************  class Card  ********************/

class Card
{

    private:
        Suit m_Suit;
    public:
        Card()  { m_Suit = Suit::Clubs; }

        std::string to_string() 
        {
            return ::to_string(m_Suit);
        }
};

int main()
{
    std::cout << Card().to_string() << '\n';
    return (0);
}

输出:

calling 'to_string' function with Suit as parameter

Live Demo on coliru

© www.soinside.com 2019 - 2024. All rights reserved.