在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么
can we use static instead of friend in this case and what are the other solutions
当我在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](强调是我的(。
运算符函数应是非静态成员函数,或者是具有至少一个参数的非成员函数,该参数的类型为类、对类的引用、枚举或对枚举的引用。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 结构和双指针隐藏在其他结构中,多层混淆
- UE4在OnComponentBeginOverlap上铸造其他actor
- 在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么
- 作为其他班级的朋友的私人功能
- 只能由其他类创建的类,而无需使用朋友
- 朋友拥有自己的类模板和其他模板参数
- 模板类构造函数作为其他模板类的朋友
- 在没有朋友c++的情况下访问其他类的私有数据