运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
Error while operator overloading (error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const char [2]’)
#ifndef NAME_H
#define NAME_H
#include <string> // For string class
class Name
{
private:
std::string first{};
std::string second{};
public:
Name(const std::string& name1, const std::string& name2) : first(name1), second(name2){}
Name()=default;
std::string get_first() const {return first;}
std::string get_second() const { return second; }
friend std::istream& operator>>(std::istream& in, Name& name);
friend std::ostream& operator<<(std::ostream& out, const Name& name);
};
// Stream input for Name objects
inline std::istream& operator>>(std::istream& in, Name& name)
{
return in >> name.first >> name.second;
}
// Stream output for Name objects
inline std::ostream& operator<<(std::ostream& out, const Name& name)
{
//My error is here while I am adding " " in the overload
return out << name.first << " " << name.second;
}
我想重载 <<
运算符,因为它将 Name 对象作为我的右手参数std::ostream
。
现在,当我在重载中添加" "时,它向我显示错误
错误是这样的:
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const char [2]’)
return out << name.first << " " << name.second;
^
感谢您上传所有详细信息 - 这个问题现在可以回答了。
编译器无法访问您提供的重载,因为istream
和ostream
在编译时不是完整的类型。
你需要写
#include <iostream>
来纠正这一点。有时编译器诊断很迟钝。