题外话:我想问一下,问这种问题的地方合适吗?
问这种“天真的”问题更合适的地方是什么?我想要一个网站或其他东西。谢谢。现在我的问题:
我的任务是编写 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/