使用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 (将#修改为@)