Here is a C++ code, it is simple, but I get error which I don't understand.
I don't know how else to use overloaded operator (), but the way I did.
Program should do the following.
Type your word: Programming
n: 5
P
Pr
Pro
Prog
Progr
Error I get:
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)
}
std::ostream& operator<<(std::ostream& out,Word& s)should bestd::ostream& operator<<(std::ostream& out,const Word& s)frienddeclaration accordingly?friend std::ostream& operator<<(std::ostream&,const Word&);