超载问题<<操作员

发布于 2024-12-09 23:23:19 字数 893 浏览 1 评论 0 原文

我正在尝试超载 <<我的货币类的运算符,但我收到此编译器错误:C2143:语法错误:缺少 ';'在 '&' 之前

在我的 .h 文件中,我有:

 friend ostream &operator << (ostream &, const Currency&);

在我的Currency.cpp 文件中,我有:

    ostream &operator << (ostream &stream, const Currency &obj){
      stream<<"$"<<obj.dollars<<"."<<obj.cents;
      return stream;
      }

到目前为止,一切都工作正常,但一旦我将其放入,就会窒息:

我在顶部有以下内容我的 .h 文件:

    #ifndef CURRENCY_H
    #define CURRENCY_H

  #include<iostream>
  #include<string>
  #include<ostream>
  #include<sstream>

  class Currency; //forward delcaration

  //Function prototypes for overloaded stream operators
  ostream &operator << (ostream &, const Currency &);

我不知道我做错了什么。帮助会很棒。谢谢

I am trying to overload the << operator for my Currency class but I get this compiler error: C2143: syntax error : missing ';' before '&'

In my .h file I have:

 friend ostream &operator << (ostream &, const Currency&);

And in my Currency.cpp file I have:

    ostream &operator << (ostream &stream, const Currency &obj){
      stream<<"$"<<obj.dollars<<"."<<obj.cents;
      return stream;
      }

Everything up until now worked fine, but choked once I put that in:

I have the following at the top of my .h file:

    #ifndef CURRENCY_H
    #define CURRENCY_H

  #include<iostream>
  #include<string>
  #include<ostream>
  #include<sstream>

  class Currency; //forward delcaration

  //Function prototypes for overloaded stream operators
  ostream &operator << (ostream &, const Currency &);

I have no idea what I am doing wrong. Help would be great. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回忆凄美了谁 2024-12-16 23:23:19

ostreamnamespace std 中声明,并且您在它之前缺少 std:: 标识符:

std::ostream &operator << (std::ostream &, const Currency &);

如果您想避免 std::< /code> 然后在头文件之后,您可以放置​​ using namespace 语句:

...
#include<ostream>
using namespace std;  // this is not desirable though in real world programming

ostream &operator << (ostream &, const Currency &);

编辑: using namespace <> 在实际编程中不建议使用在文件顶部。我把这部分仅供参考。

ostream is declared in namespace std and you are missing std:: identifier before it:

std::ostream &operator << (std::ostream &, const Currency &);

If you want to avoid std:: then after header file you can put using namespace statement:

...
#include<ostream>
using namespace std;  // this is not desirable though in real world programming

ostream &operator << (ostream &, const Currency &);

Edit: using namespace <> is not recommended in real world programming at the file top. I have put that part just for FYI.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文