c++ - 如何为类声明友元函数?

标签 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);
    }
}

最佳答案

你想用

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& 传递。

关于c++ - 如何为类声明友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355395/

相关文章:

php - 为什么返回此命名空间\类调用错误?

c++ - 无法理解 gluLookAt 参数

C++ 模板 : problem with member specialization

javascript - 从javascript中的函数更新全局变量

jquery 通过隐藏其他 div 在 DIV 上切换()

C++ 成员函数与自由函数

c++ - 由于加号或减号,if/else 语句输出未显示正确的消息

C++ 在 Unicode 而不是 Ansi 中创建文件

class - 如何通过 while/for 循环创建一个类的多个精确实例(以访问它们的属性)?

python - 使用特定字典初始化从类构建的对象