Overloading << error - c++

I am kind of newbie to programming migrated from legacy turbo c++ to VS C++2012,I have a tough time catching up and i wanted to emulate the string library for TC. But i cant make the insertion operator work in this code....Please help Out. Could you tell the mistake i made in this code. And also why are we returning the object via reference for overloading.
#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;
}

You should declare operator<< as a non-member function, because ostream will be taken as the 1st argument for operator<<, a user define type's member function can't satisfy it.
namespace String
{
class string
{
...
public:
ostream& put(ostream &sout) { sout << word; return sout; }
};
ostream& operator<<(ostream& sout, string Show) { return Show.put(sout); }
}

The output operator << has to be overloaded in the namespace, not the class itself if you want to be able to use it like so:
cout << my_class_object;
So, in the declaration of your class (string.h) add this line:
ostream &operator<<(ostream & sout,const string & Show);
And then in the definition file (string.cpp) in your namespace, not the class itself, ad this function:
ostream & operator<<( ostream & out, const bigint & data )
{
// the printing implementation
}

Related

how to write operator overloading for operator [] in c++

I want to make three[0]='p'; work in the code below. I think I have to make an operator overloading for that but I don't know how to do. What I want to get is to change first index of "Lottery winner!" to 'p'. (To get "pottery winner!").
#include<iostream>
#include<cstring>
using namespace std;
class str
{
char* a;
public:
str(char *aa=""){
this->a = new char[strlen(aa)+1];
strcpy(a,aa);
}
~str(){
delete a;
}
friend ostream& operator<<(ostream &out, str &aa);
friend istream& operator>>(istream &in, str &aa);
};
ostream& operator<<(ostream &out, str &aa){
out<<aa.a;
return out;
}
istream& operator>>(istream &in, str &aa){
in>>aa.a;
return in;
}
void main(){
str three("Lottery winner!");
three[0]='p';
cout<<three<<endl;
}
This is the general signature of the operator[]:
T& operator[](any_type);
In your context it would look like this:
struct str {
...
char& operator[](std::size_t pos) {
return a[pos];
}
};
class str
{
// ...
public:
// ...
char& operator[] (int x)
{
// add array out-of-bounds check here if you like to ...
return a[x];
}
}
operator char*()
{
return a;
}
Could also work

Overloading the << operator and problems with add function

So I recently got back into programming, in prep for my last year of physics and i'm having some trouble with an example.
It says I need to add the specific Exhibit class shown in the code, and then implement the functions. Then it wants me to display this as the output;
Max says Eeeeep
Jack says Roar
Petals says Woof
{ Max Jack Batty Sheepy Hippopotamusesy Turkey }
{ Max Jack Batty Sheepy Hippopotamusesy Turkey }
By overloading the << operator.
I've had a go, but im just stuck I believe i'm also doing the add() function incorrectly, so if someone could provide me with some insight it would be much appreciated.
Code:
#include <iostream>
#include <string>
using namespace std;
//------------------------------------------------------------
class Animal
{
private:
string name;
string sound;
public:
Animal(const string& n = "", const string& s = "");
~ Animal();
string getName() const {return name;}
string makeSound() const{return sound;}
};
Animal::Animal(const string&n, const string &s)
{
name=n;
sound=s;
}
Animal:: ~ Animal() //Destructor
{
}
ostream &operator <<(ostream& out, Animal & obj)
{
cout <<obj.getName()<<" says "<<obj.makeSound() ;
return out;
}
//------------------------------------------------------------
class Exhibit{
public:
Exhibit(int maxEnt = 10);
~Exhibit();
void add(const Animal& e);
Animal& operator [](size_t i){ return entries[i];};
friend ostream& operator <<(ostream& out, const Exhibit& obj);
private:
int MaxNumberOfAnimals;
int CurrentNumberOfAnimals;
Animal* entries;
};
Exhibit::Exhibit(int maxEnt)
{
MaxNumberOfAnimals=maxEnt;
}
Exhibit:: ~ Exhibit()
{
}
void add(const Animal& e)
{
int j=0;
entries[j]=e;
j++;
return;
}
ostream& operator <<(ostream& out, const Exhibit& obj)
{
cout <<"{ ";
for(int i=0;i++;i!=obj.MaxNumberOfAnimals)
{
cout << obj.entries[i] << ", ";
}
cout << "}"<<endl;
return out;
}
//------------------------------------------------------------
int main()
{
Animal* monkey = new Animal("Max", "Eeeeep");
Animal* tiger = new Animal("Jack", "Roar");
Animal* Dog = new Animal("Petals", "Woof");
cout << *monkey <<endl;
cout << *tiger <<endl;
cout << *Dog << endl;
Exhibit cage(10);
cage.add(*monkey);
cage.add(*tiger);
/*cage.add(Animal("Batty", "Screech"));
cage.add(Animal("Sheepy", "Bleat Bleat"));
cage.add(Animal("Hippopotamusesy", "growl"));
cage.add(Animal("Turkey","Gobble"));*/
cout << cage << endl;
cout << cage << endl;
delete monkey;
delete tiger;
delete Dog;
system("pause");
return 0;
}
//------------------------------------------------------------
One things that could be causing the problem with your << overloading is that you are sending everything to cout, rather than the out stream you pass in. A potential fix there could be changing "cout" to "out", as below:
ostream &operator <<(ostream& out, Animal & obj)
{
out <<obj.getName()<<" says "<<obj.makeSound() ;
return out;
}
As for your add function in your Exhibit class, it looks like you are initializing your counter 'j' each time you call the function, which means that it will always be 0. You can fix this by making your counter a private data member of the Exhibit class, or perhaps just by using your 'int CurrentNumberOfAnimals' to keep track, like below:
void add(const Animal& e)
{
entries[CurrentNumberOfAnimals]=e;
CurrentNumberOfAnimals++;
return;
}
There may be other errors in there that I didn't notice, but there are some.
Edit:
As posted in an above answer, entries is not initialized correctly. If you can, use a vector of Animals, like below:
#include <vector> //This should be in your Exhibit header file
class Exhibit{
public:
Exhibit(int maxEnt = 10);
~Exhibit();
void add(const Animal& e);
Animal& operator [](size_t i){ return entries[i];};
friend ostream& operator <<(ostream& out, const Exhibit& obj);
private:
int MaxNumberOfAnimals;
int CurrentNumberOfAnimals;
vector<Animal> entries;
};
This also simplifies your add function, though, see below:
void add(const Animal& e)
{
entries.push_back(e);
return;
}
2nd Edit:
So far as I can tell, this is how to do it using arrays. This is assuming that you need at most 10 animals in your "entries" array, since you have "int maxent = 10" in your original Exhibit class.
Your Exhibit class declaration could look like this (we shouldn't need the "int maxent" in your constructor anymore unless you need it for other reasons):
class Exhibit{
public:
Exhibit();
~Exhibit();
void add(const Animal& e);
Animal& operator [](size_t i){ return entries[i];};
friend ostream& operator <<(ostream& out, const Exhibit& obj);
private:
int MaxNumberOfAnimals;
int CurrentNumberOfAnimals;
Animal entries[10];
};
Your add function could then look like the first add function above, repasted here for convenience:
void add(const Animal& e)
{
entries[CurrentNumberOfAnimals]=e;
CurrentNumberOfAnimals++;
return;
}
entries[j] = e; - that's undefined behavior right there, because entries is uninitialized pointer (which results from junk data) and you're trying to access memory location which is pointed to by that invalid pointer.
If you can use std::vector, use it. Otherwise, your Exhibit class would need to partially implement one - allocation, deallocation, reallocation, deep copy if you want copyable Exhibit...

lexical cast from user defined type to int

I am trying to use boost::lexical_cast to convert my user defined type into an integer.
However, I get an exception. What am I missing??
class Employee {
private:
string name;
int empID;
public:
Employee() : name(""), empID(-1)
{ }
friend ostream& operator << (ostream& os, const Employee& e) {
os << e.empID << endl;
return os;
}
/*
operator int() {
return empID;
}*/
};
int main() {
Employee e1("Rajat", 148);
int eIDInteger = boost::lexical_cast<int>(e1); // I am expecting 148 here.
return 0;
}
I know I can always use the conversion operator, but just wondering why lexical cast doesn't work here.
The problem is that what you insert into the output stream is not the representation of an integer (because of the trailing << std::endl). The following fails in a similar way:
boost::lexical_cast<int>("148\n")
Removing the << std::endl makes it work:
friend std::ostream& operator << (std::ostream& os, const Employee& e) {
os << e.empID;
// ^^^^^^^^^^^^^^
// Without << std::endl;
return os;
}

Overloading C++ Insertion Operator (<<) for a class

I'm trying to write a class that overloads the insertion operator but in my header file I get the error.
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
Here is my code:
.h file
ostream & operator<<(ostream & os, Domino dom);
.cpp file
ostream & operator<< (ostream & os, Domino dom) {
return os << dom.toString();
}
I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?
You probably put your operator<< inside a class declaration. That means it takes an extra hidden parameter (the this parameter). You need to put it outside of any class declaration.
The insertion operator (<<) can be used as a member function or a friend function.
operator << used as a member function
ostream& operator<<(ostream& os);
This function should be invoked as :
dom << cout;
In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.
operator << used as a friend function
friend ostream& operator<<(ostream& os, const Domino& obj);
This function should be invoked as :
cout << dom;
In this case the object dom is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.
/*insertion and extraction overloading*/
#include<iostream>
using namespace std;
class complex
{
int real,imag;
public:
complex()
{
real=0;imag=0;
}
complex(int real,int imag)
{
this->real=real;
this->imag=imag;
}
void setreal(int real)
{
this->real=real;
}
int getreal()
{
return real;
}
void setimag(int imag)
{
this->imag=imag;
}
int getimag()
{
return imag;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};//end of complex class
istream & operator >>(istream & in,complex &c)
{
int temp;
in>>temp;
c.setreal(temp);
in>>temp;
c.setimag(temp);
return in;
}
ostream &operator <<(ostream &out,complex &c)
{
out<<c.getreal()<<c.getimag()<<endl;
return out;
}
int main()
{
complex c1;
cin>>c1;
// c1.display();
cout<<c1;
//c1.display();
return 0;
}

Passing a node as an outstream operator

This prints an error message about qualifiers but don't really understand what that means and how to adjust the code for it to work? Anyways, thanks a lot for looking at the code.
Note: The ostream operator is friended in the Node class.
using namespace std;
ostream& operator(ostream& output, const Node* currentNode)
{
return output;
}
void Node::nodeFunction()
{
//This node has items attached to the 'this' statement. After
//the necessary functions, this is called to output the items.
cout << this;
}
Your overloaded stream operator declaration should be like this:
std::ostream& operator<<(std::ostream& os, const T& obj);
^^^^^^^^^^^^^
You should be returning a reference to object of std::ostream, the & is wrongly placed in your overloaded function prototype.
Have a look at the working sample here.
Adding the source code here, for completeness.
Note: I have taken class Node members as public for ease of demonstration.
#include<iostream>
using namespace std;
class Node
{
public:
int i;
int j;
void nodeFunction();
friend ostream& operator <<(ostream& output, const Node* currentNode);
};
ostream& operator<<(ostream& output, const Node* currentNode)
{
output<< currentNode->i;
output<< currentNode->j;
return output;
}
void Node::nodeFunction()
{
//This node has items attached to the 'this' statement. After
//the necessary functions, this is called to output the items.
cout << this;
}
int main()
{
Node obj;
obj.i = 10;
obj.j = 20;
obj.nodeFunction();
return 0;
}
The & on the return value of the operator is in the wrong place, and it's generally better to use references rather than pointers for ostream operators:
ostream& operator<<(ostream &output, const Node &currentNode)
{
// Output values here.
return output;
}
void Node::nodeFunction()
{
cout << *this;
}