如何修复C++中的" No viable overloaded '=' "

How to fix " No viable overloaded '=' " in C++

本文关键字:overloaded No 何修复 C++ 中的 viable      更新时间:2023-10-16

此函数的目的是将.txt文件的各个行放入不超过 20 的数组中。但是,我不知道如何在无法将循环中的每一行分配给该数组的情况下进行。

int read_file(string file_name, person map[20], int 
line_limit)
{
int line_count = 0;
string x;
person specific;

顺便说一句,person类有2个名为first_name和last_name的字符串以及1个名为age的整数。StackOverflow不允许我发布我猜的整个程序。

fstream input_file;

input_file.open(file_name, ios::in); 
if (input_file.is_open())
{
cout << "WORKING" << endl;
//Loop through .txt file
while (!input_file.eof() && line_count < 
line_limit)
{
if (input_file.good())
{
input_file >> x;
map[line_count] = x;   

上面的行派生"没有可行的重载'='"错误。

line_count++;
}
}
}
else
cout << "Not Working" << endl;
return 1;
return 0;
}

任何提示也很棒!

这是我正在循环浏览.txt文件。我想在循环遍历.txt文件时分配每个杉木名称、姓氏和年龄。我想将其分配给字符串 x,然后将当时 x 中的内容放入数组中,该数组是 person 类型,该数组采用参数字符串 last_name、字符串first_name和 int age。

Ann Christensen  70
Carlos Morales   68
David Bowman     45
Frank Bowman     37
John Bowman      30
Kathleen Gueller 34
Mark Bowman      42
Mark Bowman      13
Richard Bowman   47
Susan Cox        36
class person
{

private:
string first_name;
string last_name;
int age;
//Person Constructor - Empty
public:
person()
{
first_name = "";
last_name = "";
age = 0;
//void get(istream &);
//void put(ostream &);
//bool operator = ();
}

您正在尝试将字符串分配到应该容纳person对象的位置。这将尝试执行 1,或者,如果失败,则继续执行 2。

  1. 将字符串转换为person,使用由类person定义的转换

    ,看起来像operator string()
  2. 使用方法operator=(string)将字符串分配给person。这必须在person类中定义。

另一种选择,因为我认为您要做的是分配给特定成员,是定义一个 setter 方法。通常,如果你为first_name定义一个 setter,并且会first_name分配给接受的参数,这看起来像set_first_name(string)。基本上,您只需要一些方法来设置类外first_name

如果要将一个字符串分配给另一个字符串,则不会收到operator=错误。这只发生在用户定义的类上。