如何为一个类声明一个朋友函数?

时间:2018-11-17 20:43:20

标签: c++ function class friend

离题:我想问一下,这是问这种问题的合适地方吗?

问这种“天真”问题更合适的地方是什么?我想要一个网站或其他东西。谢谢。现在我的问题是:

我的任务是编写 check_name 函数(this问题)。

我得到错误:在此范围内未声明'first_name' 已解决

编辑:我只是意识到这还不够,我必须在字符串中找到一个字符后才删除每个字符...

这是代码。谢谢。

#include <iostream>
#include <string>

using namespace std;

class student
{
private:
    string first_name;
    string last_name;

public:
    void set_name(string f, string l)
    {
        first_name = f;
        last_name = l;
    }

    friend void check_name(student k);
};

bool isInside(const string &str, char c)
{
    return str.find(c) != string::npos;
}

void check_name(student k)
{
    bool ok = true;
    for(int i = 0; i < first_name.size(); i++)
    {
        if(!isInside(last_name, first_name[i])) 
        {
            ok = false;
            break;
        }
    }
    if (ok) cout << "ANAGRAM" << endl;
    else cout << "NOT ANAGRAM" << endl;
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        string f, l;
        cin >> f >> l;
        student s;
        s.set_name(f, l);
        check_name(s);
    }
}

1 个答案:

答案 0 :(得分:2)

您要使用

void check_name(student k)
{
    bool ok = true;
    for (int i = 0; i < k.first_name.size(); i++)
//                      ^^
    {
        if (!isInside(k.last_name, k.first_name[i]))
//                    ^^           ^^
        {
            ok = false;
            break;
        }
    }
    if (ok) cout << "ANAGRAM" << endl;
    else cout << "NOT ANAGRAM" << endl;
}

由于您的check_name()仅读取k,因此您可能希望将其作为student const&传递。

相关问题