提问者:小点点

如何重新定义Operator>>将数据从键盘写入我的个人类? [副本]


我想重新定义运算符>;>; 但我有些问题。 这是运算符重定义(包含在personal.cpp中):

void Person::operator>>(std::istream)
{
    QTextStream in(stdin);
    std::cout << (char*)"Name: ";
    in >> this->Name >> Qt::endl;
    std::cout << (char*)"Phone number: ";
    in >> this->Phone_num >> Qt::endl;
    std::cout << (char*)"Address: ";
    in >> this->Address >> Qt::endl;
    return;
}

当我试着

    Person Vasya;
    std::cin >> Vasya;

我有以下错误

C:\qt\examples\my\custom_project\main.cpp:5:unda.undug curca:二进制表达式('std::istream'(又名'basic_istream')和'person')的操作数无效。

我做错了什么?

我不能用这样的结构

std::istream& operator>> (std::istream &in, Person &p)
{
    // Since operator>> is a friend of the Point class, we can access Point's members directly.
    // note that parameter point must be non-const so we can modify the class members with the input values
    in >> p.Name >> Qt::endl;
    in >> p.Phone_num >> Qt::endl;
    in >> p.Address >> Qt::endl;
    return in;
}

由于“二进制表达式('std::istream'(又名'basic_istream')和'Qstring')的操作数无效”错误


共3个答案

匿名用户

您不能真正将运算符>>重载为成员,因为当使用它时,它的成员必须位于表达式的左手边,这将需要看起来很奇怪

vasya >> std::cin;

此外,您必须通过引用传递流并通过引用返回它(用于链接)。 因此,您需要:

std::istream& operator>> (std::itstream& in, Person& p)
{
   // Read in fields
   ...

   return is;
}

也值得让这个人成为朋友。

匿名用户

这在互联网上是一种常见的做法。 我发现了这个关于重载I/O运算符的教程,我想你可能会发现它很有用。 另外,我觉得你的功能可能是这样的:

std::istream& operator>> (std::istream &in, Person &p)
{
    // Since operator>> is a friend of the Point class, we can access Point's members directly.
    // note that parameter point must be non-const so we can modify the class members with the input values
    in >> p.Name >> Qt::endl;
    in >> p.Phone_num >> Qt::endl;
    in >> p.Address >> Qt::endl;
    return in;
}

匿名用户

您的代码中至少有两个问题。 运算符>>不能是成员函数。 这在复本和其他答案中都有解释。

但错误信息

invalid operands to binary expression ('std::istream' (aka 'basic_istream<char, char_traits >') and 'QString')

来自

in >> p.Name >> Qt::endl;

您不能写入qt::endl

应该是

class Person {
// some code
public:
// some code
    friend std::istream &operator>>(std::istream &in, Person &p) {
    // Since operator>> is a friend of the Point class, we can access Point's members directly.
    // note that parameter point must be non-const so we can modify the class members with the input values
        std::string Name, Phone_num, Address;
        in >> Name >> Phone_num >> Address;
        p.Name = QString::fromStdString(Name);
        p.Phone_num = QString::fromStdString(Phone_num);
        p.Address = QString::fromStdString(Address);
        return in;
    }
// some code
};