当前位置:网站首页>Overloading of typical operators
Overloading of typical operators
2022-06-13 09:26:00 【Ritian juvenile wzh】
Overloading of typical operators
structure “ fraction ” class
example : Construct a “ fraction ” class Fraction
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdlib>
using namespace std;
class Fraction {
//Fraction Class represents a fraction
private:
void simplify(); // Simplified score
int nume,deno; // molecular nume, The denominator deno
public:
Fraction(int n=0,int d=1) : nume(n),deno(d) {
simplify();
}
Fraction(double d); //double Type conversion Fraction Constructors
Fraction(const string& str); //string Type conversion Fraction Constructors
Fraction(const Fraction& f) : nume(f.nume),deno(f.deno) {
} // copy constructor
void display(); // Show scores
};
Fraction::Fraction(const string& str) : nume(0),deno(1) {
// example : character string "2/3" Convert to fractional class
char buf[200];
int i=str.find('/'),j=str.length()-i-1;
if(i>=0) {
str.copy(buf,i,0); buf[i]=0; nume=atoi(buf); // The preceding string is converted to a numerator
str.copy(buf,j,i+1); buf[j]=0; deno=atoi(buf); // The following string is converted to the denominator
}
simplify(); // Normalized score
}
Fraction::Fraction(double d) : nume(d),deno(1) {
// The initial molecule is d The integral part of
d=d-nume; //d Decimal part of example :0.25
while(int(d*10)!=0) {
//0.25>=25/100
nume=nume*10+int(d*10);
deno=deno*10;
d=d*10-int(d*10);
}
simplify(); // Normalized score
}
void Fraction::display() {
// Show normalized scores
if(deno!=0 && deno!=1 && nume!=deno)
cout<<nume<<"/"<<deno<<endl;
else
cout<<nume<<endl; // When there is a nume/0,nume/1,nume/nume Show only when nume
}
void Fraction::simplify() {
// Score normalization
int m,n,r,s=1;
if(nume!=0 && deno!=0) {
// The denominator cannot be 0
if(deno<0) s=-s,deno=-deno; // The denominator is a positive number
if(nume<0) s=-s,nume=-nume; // The numerator is positive
//s Is a fraction symbol , The symbol is on the numerator
m=nume,n=deno;
while(n!=0)
r=m%n,m=n,n=r;
// seek nume and deno Maximum common divisor of m
if(m!=0)
nume=s*nume/m,deno=deno/m;
// The numerator and denominator remove the common divisor
}
else
nume=0,deno=1; // The numerator or denominator is 0 When normalized to molecules =0, The denominator =1
}
int main()
{
Fraction a(1,2),b(0.25),c("6/9");
a.display(); // Output 1/2
b.display(); // Output 1/4
c.display(); // Output 2/3
return 0;
}
Overloading of typical operators
1. Overloaded compound assignment operators
The compound assignment operator has “ Reassign an operand ” The function of , So the operator function needs to return the reference type
for example :a+=b amount to a=a+b
Design the compound assignment operator as Fraction Public member function of :
Define overloaded operator statements within a class :
Fraction& operator += (const Fraction& b) {
//a+=b
nume=nume*b.deno+deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
Fraction& operator -= (const Fraction& b) {
//a-=b
nume=nume*b.deno-deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
2. Overload stream operators
User defined data types , You can't use it directly << and >> For input and output . If you want to use them to import and export data of custom data types , They must be overloaded
Yes << and >> Overloaded functions are defined by the standard library iostream Stipulated , Form the following :
ostream& operator <<(ostream& os,const Class types &obj) {
os<<..... //obj Data members are output one by one
return os; // Must return ostream object
}
istream& operator >>(istream& is, Class types &obj) {
is>>..... // Input one by one obj Data member
return is; // Must return istream object
}
The reason why both functions return the reference type of the stream object , This is because both stream insertion and stream extraction require continuous input or output , Such as cout<<a<<b<<c; So the operand should be able to be an lvalue
Stream insert and extract overloaded functions cannot be member functions of a class , Otherwise, the left operand can only be an object of this type , The following error form will appear :
a<<cout perhaps a>>cin
If you want to support normal forms , The left operand must be ostream Type or istream type
ostream& operator<<(ostream& os,const Fraction& a) {
//os<<a
// Explicitly normalized fractions
if(a.deno!=0 && a.deno!=1 && a.nume!=a.deno) {
os<<a.nume<<"/"<<a.deno;
}
else {
// When there is a nume/0,nume/1,nume/nume Show only when nume
os<<a.nume;
}
return os; // Must return ostream object
}
istream& operator>>(istream& is,Fraction& a) {
//is>>a
char ch;
is>>a.nume>>ch>>a.deno; // Press molecular / The denominator Form input data
return is; // Must return istream object
}
3. Overloaded type conversion operator
C+ There are already implicit type conversions for basic data types , There is also display type conversion , We can convert a specified data type to a class type by constructing a constructor for a single parameter :
Fraction(double d); and Fraction(const string& str);
If you want to explicitly convert a class type to another data type , You need to overload the type conversion operator
Type conversion operator functions can only be used as member functions of classes , Because the converted operand is an object of a class . for example :
Fraction::operator double() {
return (double)nume/deno;
}
" Fraction class " The complete code is as follows :
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<ostream>
#include<istream>
using namespace std;
class Fraction {
//Fraction Class represents a fraction
private:
void simplify(); // Simplified score
public:
int nume,deno; // molecular nume, The denominator deno
Fraction(int n=0,int d=1) : nume(n),deno(d) {
simplify();
}
Fraction(double d); //double Type conversion Fraction Constructors
Fraction(const string& str); //string Type conversion Fraction Constructors
Fraction(const Fraction& f) : nume(f.nume),deno(f.deno) {
} // copy constructor
void display(); // Show scores
Fraction& operator += (const Fraction& b) {
//a+=b
nume=nume*b.deno+deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
Fraction& operator + (const Fraction& b) {
//a+=b
nume=nume*b.deno+deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
Fraction& operator -= (const Fraction& b) {
//a-=b
nume=nume*b.deno-deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
Fraction& operator - (const Fraction& b) {
//a-=b
nume=nume*b.deno-deno*b.nume;
deno=deno*b.deno;
simplify();
return *this; // Returns the left operand
}
operator double();
};
Fraction::Fraction(const string& str) : nume(0),deno(1) {
// example : character string "2/3" Convert to fractional class
char buf[200];
int i=str.find('/'),j=str.length()-i-1;
if(i>=0) {
str.copy(buf,i,0); buf[i]=0; nume=atoi(buf); // The preceding string is converted to a numerator
str.copy(buf,j,i+1); buf[j]=0; deno=atoi(buf); // The following string is converted to the denominator
}
simplify(); // Normalized score
}
Fraction::Fraction(double d) : nume(d),deno(1) {
// The initial molecule is d The integral part of
d=d-nume; //d Decimal part of example :0.25
while(int(d*10)!=0) {
//0.25>=25/100
nume=nume*10+int(d*10);
deno=deno*10;
d=d*10-int(d*10);
}
simplify(); // Normalized score
}
void Fraction::display() {
// Show normalized scores
if(deno!=0 && deno!=1 && nume!=deno)
cout<<nume<<"/"<<deno<<endl;
else
cout<<nume<<endl; // When there is a nume/0,nume/1,nume/nume Show only when nume
}
void Fraction::simplify() {
// Score normalization
int m,n,r,s=1;
if(nume!=0 && deno!=0) {
// The denominator cannot be 0
if(deno<0) s=-s,deno=-deno; // The denominator is a positive number
if(nume<0) s=-s,nume=-nume; // The numerator is positive
//s Is a fraction symbol , The symbol is on the numerator
m=nume,n=deno;
while(n!=0)
r=m%n,m=n,n=r;
// seek nume and deno Maximum common divisor of m
if(m!=0)
nume=s*nume/m,deno=deno/m;
// The numerator and denominator remove the common divisor
}
else
nume=0,deno=1; // The numerator or denominator is 0 When normalized to molecules =0, The denominator =1
}
ostream& operator<<(ostream& os,const Fraction& a) {
//os<<a
// Explicitly normalized fractions
if(a.deno!=0 && a.deno!=1 && a.nume!=a.deno) {
os<<a.nume<<"/"<<a.deno;
}
else {
// When there is a nume/0,nume/1,nume/nume Show only when nume
os<<a.nume;
}
return os; // Must return ostream object
}
istream& operator>>(istream& is,Fraction& a) {
//is>>a
char ch;
is>>a.nume>>ch>>a.deno; // Press molecular / The denominator Form input data
return is; // Must return istream object
}
Fraction::operator double() {
return (double)nume/deno;
}
int main()
{
Fraction a,b(1,2);
a=1.25;
cout<<(double)(a+b)<<endl; // Output 1.75
return 0;
}
边栏推荐
- 批量讀取文件夾下的全部語音文件
- Jenkins接入Openldap用戶認證
- acwing 788. Number of pairs in reverse order
- Jenkins integrates LDAP. The problem of login failure of Jenkins users caused by LDAP configuration error is solved
- Acwing 787. Merge sort
- 谨记! 写代码别太自信! 一定要写点关键日志info输出,不然问题都定位不到。
- @Value不生效及extend/implement其他类无法注入bean的手动注入
- 线上调试工具Arthas基础
- LeetCode 6096. Success logarithm of spells and potions (binary search)
- JUC atomic integer
猜你喜欢

acwing 788. Number of pairs in reverse order
![[implementation of depth first search]](/img/10/4f150e4fa0d4edf01483a72b881afe.jpg)
[implementation of depth first search]

攻防世界PWN play 条件竞争漏洞的利用

(tree DP) acwing 285 A dance without a boss

C/s model and P2P model

C language: minesweeping

C language: recursive function to realize Hanoi Tower

Jenkins access openldap user authentication

Yolov5 face learning notes

BGP Federation +community
随机推荐
[most comprehensive and detailed explanation] detailed explanation of knapsack problem
C language: dynamic memory management
Jenkins接入Openldap用户认证
Acwing785. quick sort (sort+ quick sort + merge sort)
线上调试工具Arthas高级
LeetCode 202. 快乐数
线上调试工具Arthas基础
7-3 virus traceability (20 points)
Class and object -- friend
C language: timer principle
【最全面详细解释】背包问题详解
Haproxy + keepalived for high availability load balancing of MySQL
BGP 联邦+Community
20211108 det(AB)=det(A)det(B)
攻防世界PWN play 条件竞争漏洞的利用
Online debugging tool Arthas advanced
(state compression dp+ binary) acwing 91 Shortest Hamilton path
LeetCode 343. integer partition
Calculate the number of days between two times (supports cross month and cross year)
(dp+ memory) acwing 901 skiing