在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么

can we use static instead of friend in this case and what are the other solutions

本文关键字:朋友 其他 是什么 解决方案 我们 这种情况下 可以使 静态      更新时间:2023-10-16

当我在PhoneNumber.h中使用friend作为运算符函数时,电话号码.cpp表现良好。但是对于静态,它无法编译(为什么?(以及声明它的其他方法是什么(即(除了朋友之外的所有方法。

电话号码.h

#include<iostream>
#include <string>
#include<iomanip>
using namespace std;
class PhoneNumber{
public:
string areaCode, exchange, line;
static ostream& operator<<(ostream &output, const PhoneNumber&);
static istream& operator>>(istream &input, PhoneNumber&);
};

电话号码.cpp

#include"PhoneNumber.h"
using namespace std;
ostream& PhoneNumber::operator<<(ostream &output, const PhoneNumber& obj){
output << "(" <<obj. areaCode << ") "
<< obj.exchange << "-" << obj.line;
return output;
};

istream& PhoneNumber::operator>>(istream &input, PhoneNumber&obj){
input.ignore(); 
input >> setw( 3 ) >> obj.areaCode;
input.ignore( 2 );
input >> setw( 3 ) >> obj.exchange;
input.ignore();
input >> setw( 4 ) >> obj.line;
return input;
};

主.cpp

#include"PhoneNumber.h"
using namespace std;
int main(){
PhoneNumber phone;
cout << "Enter phone number in the form (123) 456-7890:" << endl;
cin>>phone;
cout << "The phone number entered was: ";
cout<<phone;cout << endl;
int y;cin>>y;
return 0;}

重载运算符不能是静态成员函数,请参阅 [over.oper](强调是我的(。

运算符函数应是非静态成员函数,或者是具有至少一个参数的非成员函数,该参数的类型为类、对类的引用、枚举或对枚举的引用。