Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
OperatorOverload
//g++ 7.4.0 //operator overloading: input,output, assignment, conversion & subscript //this code is created by Rezaul Hoque on September 01,2021;contact: jewelmrh@yahoo.com //note: codes shared by Rezaul Hoque on rextester are not for sale; they are created and shared to facilitate the algorithm learning process; many like Hoque use this platform to practice programming ;Rezaul hopes his contribution helps others to fine tune their learning; #include <iostream> namespace Garden{ class Vegetable{ friend std::istream & operator>>(std::istream& istr,Vegetable& in);//input operator friend std::ostream & operator<<(std::ostream& ostr ,const Vegetable& print);//output operator int l, b,m; public: Vegetable (){}//default constructor Vegetable (int vl,int vb){ l=vl; b=vb;}//Vegetable(int,int ) constructor Vegetable (const Vegetable& v){l=v.l; b=v.b;}//copy constructor Vegetable& operator=(const Vegetable& eq){ l=eq.l; b=eq.b; return *this;}//assignment operator int& operator[](int);//subscript operator operator double();//conversion operator int area(){return l*b;} }; std::istream & operator>>(std::istream & istr,Vegetable& in) { std::cout<<"\nLength: \n"; istr>>in.l; std::cout<<"\nBreadth:\n"; istr>>in.b; return istr; } std::ostream & operator<<(std::ostream & ostr,const Vegetable& print) { ostr<<"\nLength:\n"<<print.l<<"\nBreadth:\n"<<print.b; return ostr; } int& Vegetable::operator[](int i){ if (i==1) return l; if (i==2) return b; if(i==3) return m=area(); std::cerr<<"Index out of range.\n"; exit(0); } Vegetable:: operator double() { return double(l*b); } } int main(){ Garden::Vegetable x,y,z; std::cin>>x>>y;//input operator is called std::cout<<"\nx:\n"<<x<<"\ny:\n"<<y;//output operator is called z=y;//assignment operator is called std::cout<<"\nArea:\n"<<"For x:\n"; std::cout<<double(x.area());//conversion operator is called std::cout<<"\nFor y:\n"<<double(z.area()); std::cout<<"\nUse of subscript operator(index 1 for lengtg,2 for breadth and 3 for area):\n"; std::cout<<"x[1]= "<<x[1]<<";\n"<<"x[2]= "<<x[2]<<";\n"<<"x[3]= "<<x[3]<<";\n";//subscript operator is called std::cout<<"y[1]= "<<z[1]<<";\n"<<"y[2]= "<<z[2]<<";\n"<<"y[3]= "<<z[3]<<";\n"<<"y[4]= "<<y[4]; return 0; }
run
|
edit
|
history
|
help
0
sorting
NumberToWords
Tree
Handling new types without using RTTI
cppPyPoly
Полиморфизм. Простейшее ДЕМО.
gal
Exempel 2
Identifying polimorphic types without using RTTI or type mappings
LIS