Error when using overloaded operator () C ++
Here is the C ++ code, it's simple, but I get an error that I don't understand.
I don't know how to use overloaded operator ()
, but this is how I did it.
The program should do the following.
Enter word: Program
n: 5
P
Pr
Pro
Prog
Progr
Mistake:
no match for 'operator <<in' std :: cout <Word :: operator () (INT) (n)
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)
}
source to share
When you do
cout << r(i);
the compiler does the following:
- Creates a temporary variable of type
Word
- Calls
operator(int)
and commits its result - Stores the result in a temporary object
- Skips a temporary object to
operator <<
Since you don't have access to the temporary object, the compiler disallows non-permanent access to it. This is why you get the error: you are trying to pass an object that is implicitly constant for a parameter that accepts a non-permalink.
To fix this, change your signature operator<<
to canonical, i.e. take the link const
for the parameter Word&
:
friend std::ostream& operator<<(std::ostream&, const Word&);
// ^^^^^
source to share
The problem is in the signature
std::ostream& operator<<(std::ostream& out,Word& s);
This takes Word
the link.
Word operator()(int);
returns value Word
by value. In the expression
cout << r(i);
you are trying to bind a temporary value to a link that is forbidden by the language. It reference to const
can only bind to a temporary value. Change your signature operator<<
(in declaration and definition) to:
std::ostream& operator<<(std::ostream& out, const Word& s);
and it should work. It is also a smart choice as operator<<
it should not change the argument Word
.
source to share