c++ - 如何调用用于重载运算符“<<”的友元函数?
问题描述
.h 文件
class MyString{
private:
int size;
int capacity;
char *data;
public:
MyString( );
MyString(const char *);
void displayState( ostream &out );
friend ostream& operator<< (ostream&, MyString&);
};
.cpp
void MyString::displayState( ostream& out ){
out << "Size: " << this->size << endl;
out << "Capacity: " << this->capacity << endl;
out << "Data: " << this->data << endl;
}
ostream& operator << (ostream& out, MyString& myStr){
for (int i = 0; i < myStr.size; i++){
out << myStr.data[i]<<" ";
}
return out;
}
我没有拿出我的构造函数,因为我希望我能保护我的代码
主文件
char array[20] = {'1','2','4','g','1',
'2','6','b','v','c',
'b','c','b','q','b',
'p','b','q','m'};
MyString testStr2(array);
testStr2.displayState(cout);
输出是
Size: 19
Capacity: 20
Data: 124g126bvcbcbqbpbqm
我的代码想让我的输出像
Size: 19
Capacity: 20
Data: 1 2 4 g 1 2 6 b v c b c b q b p b q m
当我删除好友功能时。我的输出还是一样的。我只是不知道为什么当我调用显示函数时,运算符 << 并没有重载
解决方案
- Your title has a possible typo? You are overloading
operator<<
in code, but you are asking about overloadingoperator>>
. - If my guess of the typo is right, it's because you did not called
ostream& operator<< (ostream&, MyString&);
at all.
In yourvoid MyString::displayState( ostream& out )
function, you are calling
out << "Data: " << this->data << endl;
which is calling std::ostream& operator<<(std::ostream&, const char*)
EDIT for addition: As for how to call your function, you defined that operator<<
to accept an ostream&
and MyString&
. So you simply call it by std::cout<<testStr2;
in your main()
.
推荐阅读
- python - 如何编写代码以根据修改的最新日期自动打开目录中的最新文件?
- json - 串行显示后 JSONCPP 写入文件
- uwp-xaml - 警告 NU1603 Microsoft.NETCore.UniversalWindowsPlatform 6.2.0-preview1-26926-04
- android - Android 上的 Admob:加载前未保留横幅空间
- .net - 读取父列表的子列表
- wpf - 随着窗口大小的增加,动画变慢
- gmail-api - DotNet GMail 快速入门应用程序名称
- amazon-web-services - AWS Athena 表创建失败,“在输入‘创建外部’时没有可行的替代方案”
- image - 如何在 YOLO v3 输出显示视频中捕获框边界图像
- javascript - 网站代码在 Chrome 和 Firefox、桌面或移动设备上运行良好,但在 Safari 上无法运行