gpt4 book ai didi

c++ - 重载 << 错误

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

我是从遗留 Turbo C++ 迁移到 VS C++2012 的编程新手,我很难 catch ,我想模拟 TC 的字符串库。但我无法让插入运算符在此代码中工作....请帮忙。你能告诉我在这段代码中犯的错误吗?还有为什么我们要通过引用返回对象以进行重载。

#include<iostream>
#include<string>

namespace String
{
class string
{
char word[100];
int size;


public:
string()
{
size=0;
}
string(int sz)
{
size=sz;
}
string(char *Word)
{
strcpy(word,Word);
size=sizeof(*Word);
}
~string()
{
}
string &operator+(string Add)
{
strcat(word,Add.word);
return *this;
}

string &operator=(char *Word)
{
strcpy(word,Word);
return *this;
}
/*
ostream &operator<<(ostream &sout,string Show)
{
sout<<Show.word;

return sout;
}
*/
void Show()
{
std::cout<<word;
}
};
}

void main()
{
String::string A="ABCDEF";
String::string B="GHIJK";
String::string C;

C=A+B;

C.Show();
std::cin.ignore(2);
//std::cout<<C;
}

最佳答案

您应该将 operator<< 声明为非成员 函数,因为 ostream将作为 operator<< 的第一个参数,用户定义类型的成员函数不能满足它。

namespace String
{
class string
{
...
public:
ostream& put(ostream &sout) { sout << word; return sout; }
};

ostream& operator<<(ostream& sout, string Show) { return Show.put(sout); }
}

关于c++ - 重载 << 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602231/

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