与 std::cin 中的运算符>>不匹配
no match for operator >> in std::cin
我有一个班级员工
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class employee
{
public:
double operator + (employee);
istream& operator>> (istream&);
employee(int);
double getSalary();
private:
double salary;
};
int main()
{
employee A(400);
employee B(800);
employee C(220);
cin>>C;
}
employee::employee(int salary)
{
this->salary = salary;
}
double employee::operator + (employee e)
{
double total;
total = e.salary + this->salary;
return total;
}
double employee::getSalary()
{
return this->salary;
}
istream& employee::operator>> (istream& in)
{
in>>this->salary;
return in;
}
我试图重载输入运算符>>以读取员工对象,但我得到了以下错误
std::cin 中的运算符>>不匹配
我做错了什么???
edit:我知道如何通过朋友函数来完成,我现在正试图通过成员函数来学习如何完成
我知道如何通过朋友功能来完成,我现在正试图通过成员功能来学习如何完成
你不能。
对于二进制operator@
以及对象A a
和B b
,语法a @ b
将调用形式operator@(A,B)
的非成员函数或形式A::operator@(B)
的成员函数。没有别的。
因此,要使std::cin >> C
工作,它必须是std::istream
的成员,但由于不能修改std::istream
,因此不能将operator>>
实现为成员函数。
(除非你想变得怪异和非传统,写C << std::cin
或C >> std::cin
,但如果你这样做,其他程序员会讨厌你混淆和非传统。不要这样做。)
您需要这样声明:
class employee
{
public:
friend std::istream& operator >> (std::istream& is, employee& employee);
}; // eo class employee
实施:
std::istream& employee::operator >> (std::istream& is, employee& employee)
{
is >> employee.salary; // this function is a friend, private members are visible.
return is;
};
附带说明一下,在头文件中执行using namespace std;
通常是个坏主意。
似乎我们不能声明运算符<lt;内部类声明。我试过了,还可以。
#include <stdio.h>
#include <iostream>
using namespace std;
struct foo {
int field;
};
istream& operator >> (istream& cin, foo& a){
cin >> a.field;
return cin;
}
foo a;
main(){
cin >> a;
}
相关文章:
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 在使用累加时,C++中的运算符+不匹配
- C++ 与操作员不匹配<<
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 与'operator='不匹配(操作数类型'String'且"void")
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- C4018:类内有符号、无符号不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- RE2 不匹配非 ASCII 字符
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- OpenSSL fips in C++ wrapper Library 如何?错误:指纹不匹配
- 为什么我的数组值与此处的全局变量不匹配?
- 引号之间匹配/不匹配,带有不可避免的引号和多行
- 映射迭代器与运算符不匹配
- C++调用和定义不匹配
- 模板专用化与派生类不匹配