Jhon Willson
Jhon Willson

Reputation: 11

How do I declare a friend function for a class?

Off-Topic: I want to ask, is this the right place to ask this kind of question?

What would be a more appropriate place to ask this kind of "naive" questions? I would like a website or something. Thank you. Now my problem:

I have the task to write the check_name function (this problem).

I get the error: 'first_name' was not declared in this scope SOLVED

EDIT: I just realized this is not enough and I have to remove every char after I find one in the string...

Here is the code. Thank you.

#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);
    }
}

Upvotes: 0

Views: 45

Answers (1)

Swordfish
Swordfish

Reputation: 13134

You want to use

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;
}

Since your check_name() only reads k you might want to pass it as student const&.

Upvotes: 2

Related Questions