gpt4 book ai didi

c++ - 在这种情况下我们可以使用 static 而不是 friend 吗?其他解决方案是什么

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:02 24 4
gpt4 key购买 nike

当我在 PhoneNumber.h 中使用 friend 作为运算符函数时,PhoneNumber.cpp 表现良好。但是对于 static 它不能被编译(为什么?)以及声明它的其他方法是什么(即)除了 friend 之外的所有方法。

电话号码.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] (重点是我的)。

An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

关于c++ - 在这种情况下我们可以使用 static 而不是 friend 吗?其他解决方案是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50958499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com