【问题标题】:Error when using overloaded operator () C++使用重载运算符 () C++ 时出错
【发布时间】:2014-11-30 11:55:47
【问题描述】:

这是一个 C++ 代码,它很简单,但我得到了我不明白的错误。
我不知道如何使用重载的operator (),但我就是这样做的。
程序应执行以下操作。

输入您的单词:编程
n: 5
P
公关

程序
程序

我得到的错误:

'std::cout

Word.h

#ifndef WORD_H
#define WORD_H


class Word
            {
            private:
                    char *str;
            public:
                    Word();
                    ~Word();
                    Word operator()(int); //overloading operator ()
                    friend std::ostream& operator<<(std::ostream&,Word&);
                    friend std::istream& operator>>(std::istream&,Word&);
            };

#endif

Word.cpp

#include <iostream>
#include <cstring>
#include "Word.h"

Word::Word()
    {
    str=new char[100];
    }

Word::~Word()
    {
    delete[] str;
    }


Word Word::operator()(int d)  //overloading operator ()
    {
    Word pom;
    strncpy(pom.str,str,d);
    return pom;
    }


std::ostream& operator<<(std::ostream& out,Word& s)
    {    
    out<<s.str; return out;
    }


std::istream& operator>>(std::istream& in,Word& s)
    {
    in>>s.str; return in;
    }

main.cpp

#include<iostream>
#include "Word.h"


int main()
{
   Word r;
   std::cout<<"Type your word: "; 
   std::cin>>r;

   int n;
   std::cout<<"n:"; 
   std::cin>>n;

   for (int i=1; i<=n; i++) std::cout << r(i) << std::endl; //error when using r(i)
}

【问题讨论】:

  • std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out,Word&amp; s) 应该是std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out,const Word&amp; s)
  • 谢谢。还是不行……
  • 相应地更改了friend 声明? friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;,const Word&amp;);
  • 是的,它现在正在工作。再次感谢您。

标签: c++ compiler-errors operator-overloading


【解决方案1】:

问题是签名的

std::ostream& operator<<(std::ostream& out,Word& s);

这通过引用接受Word

Word operator()(int);

按值返回Word。在表达式中

cout << r(i);

您最终会尝试将临时值绑定到引用,这是语言所禁止的。只有reference to const 可以绑定到临时值。将您的operator&lt;&lt; 签名(在声明和定义中)更改为:

std::ostream& operator<<(std::ostream& out, const Word& s);

它应该可以工作。这也是一个明智的选择,因为operator&lt;&lt; 不应更改Word 参数。

【讨论】:

    【解决方案2】:

    当你这样做时

    cout << r(i);
    

    编译器执行以下操作:

    • 创建Word 类型的临时变量
    • 调用operator(int),并获取其结果
    • 将结果存储在临时对象中
    • 将临时对象传递给operator &lt;&lt;

    由于您无权访问临时对象,因此编译器不允许对其进行非常量访问。这就是你得到错误的原因:你试图将一个隐式常量的对象传递给一个接受非常量引用的参数。

    要解决此问题,请将 operator&lt;&lt; 的签名更改为规范签名,即为 Word&amp; 参数获取 const 引用:

    friend std::ostream& operator<<(std::ostream&, const Word&);
    //                                             ^^^^^
    

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 2012-08-21
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2014-03-18
      • 2016-09-25
      相关资源
      最近更新 更多