Pages

Showing posts with label FRIEND FUNCTION. Show all posts
Showing posts with label FRIEND FUNCTION. Show all posts

Friday, March 29, 2013

C++ program to overload the unary minus operator using friend function.

Write a program to overload the unary minus operator using friend function.

#include<iostream>
using namespace std;
class space{
  int x;
  int y;
  int z;
  public:
    void getdata(int a,int b,int c);
    void display(void);
    friend void operator-(space &s);
};
void space :: getdata(int a,int b,int c){
  x=a;
  y=b;
  z=c;
}
void space :: display(void){
  cout<<x<<" ";
  cout<<y<<" ";
  cout<<z<<"\n";
}
void operator-( space &s){
  s.x=-s.x;
  s.y=-s.y;
  s.z=-s.z;
}
int main(){
  space s;
  s.getdata(10,-20,30);
  cout<<"S : ";
  s.display();
  -s;
  cout<<"S :";
  s.display();
  return 0;
}

You might also like:

C++ PROGRAM TO DO ELECTRICITY BILL CALCULATION.

C++ PROGRAM TO READ AND DISPLAY STUDENT DETAILS USING INHERITANCE.

OUTPUT

 


Tuesday, September 18, 2012

C++ PROGRAM TO CREATE A CLASS CALLED STRING.

Write a C++ program to create a class called STRING and implement the following operations. Display the results after every operation by overloading the operator.
 
STRING s1 = “HELLO”

STRING s2 = “WORLD”

STIRNG s3 = s1 + s2 ; (Use copy constructor).

 
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
  char name[23];
  public :string()
  {
    name[23]='\0';
  }
  string(char s[])
  {
    strcpy(name,s);
  }
  string(string &s)
  {
    strcpy(name,s.name);
  }
friend string operator +(string s1, string s2);
friend ostream &operator <<(ostream  &out, string &s);
};
ostream &operator <<(ostream &out , string &s)
{
  out <<"\t"<<s.name<<endl;
  return(out);
}
string operator +(string s1, string s2)
{
  string temp(s1);
//strcat(temp.name,"");
  strcat(temp.name, s2.name);
  return(temp);
}
void main()
{
  clrscr();
  string s1("hello ");
  string s2("world");
  string s3=s1+s2;
  cout<<"\nFIRST STRING ="<<s1
      <<"\nSECOND STRING ="<<s2;
  cout<<"\nCONCATENATED THIRD STRING ="<<s3;
  getch();
}


OUTPUT