如何解决使用Friend函数解析字符串并将值返回给类
我想解析用户输入的字符串以不包含任何空格。我认为这会更容易保存到文件并再次读取。
我知道朋友可以用来访问类中的私有或受保护的数据。 我想让它对这个类起作用,这样我就只能传递一个参数,它会返回 1 个字符串,因为我希望也能在其他类中重用这个友元函数。
//Test file,for testing code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Item
{
protected:
string item_name;
string item_supplier;
int item_price;
public:
// Parsing function i.e a friend function
friend string parse_to_dash(string);
friend string parse_to_space(string);
void set_item_name(string i_name){
item_name= parse_to_dash (i_name);
}
void set_item_supplier(string i_supplier){
item_supplier= parse_to_dash (i_supplier);
}
void set_item_price(int price){
item_price = price;
}
};
string parse_to_dash (string word)
{
int i=0;
for (i; i < word.length(); i++){
if(word[i]==' ')
word[i] = '_';
}
return word;
}
string parse_to_space (string word)
{
int i=0;
for (i; i < word.length(); i++){
if(word[i]=='_')
word[i] = ' ';
}
return word;
}
// As we have completed base class lets test it
int main(){
// Checking object creation
Item items;
}
'''
我得到的错误是:
49 44 C:\Users... [错误] 'parse_to_dash' 未在此范围内声明
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。