C++实现运算符与函数重载
对于内置的数据类型,编译器可以得知其数据类型,因此通过其内置的运算符即可进行运算
当需要实现自定义的数据类型实现运算符运算时,由于编译器无法准确得知其数据类型,从而出现报错。此时的解决办法为将运算符实现重载现已加号+为例:(关键字为operator+需要重载的运算符)
#include <iostream>
using namespace std;
class Person {
public:
int a;
int b;
//成员函数重载运算符
/*Person operator+(Person &p)*/
/*{
Person temp;
temp.a = this->a + p.a;
temp.b = this->b + p.b;
return(temp);
}*/
};
//全局函数重载运算符
Person operator+(Person &p1, Person &p2)
{
Person temp;
temp.a = p1.a + p2.a;
temp.b = p1.b + p2.b;
return(temp);
}
void test() {
Person p1,p2;
p1.a = p1.b = 10;
p2.a = p2.b = 20;
Person p3 = p1 + p2;
cout << "p3.a= "<< p3.a <<endl;
cout << "p3.b= "<< p3.b <<endl;
}
int main()
{
test();
return 0;
}
上述借助成员函数以及全局函数,在自定义数据类型Person下实现加号重载。
函数的重载:
同名函数通过形参的不同类型实现函数重载。
左移运算符的重载
运算符的重载可以借助成员函数或者全局函数进行重载,左移运算符进行重载的过程中,如果使用成员函数会出现
变量名<<cout
的形式,因此可以使用全局函数来对左移运算符进行重载
#include <iostream>
using namespace std;
class Person {
//借助友元函数访问私有变量
friend ostream & operator<<(ostream &cout, Person &p);
public:
Person (int a1, int b1) {
a = a1;
b = b1;
}
private:
int a;
int b;
};
//全局函数重载运算符ostream &引用返回该类型
ostream & operator<<(ostream &cout, Person &p)
{
cout << "a= " << p.a << " b= " << p.b << endl;
return (cout);
}
void test() {
Person p(10,15);
/*p1.a = p1.b = 10;*/
cout << p << endl;
}
int main()
{
test();
return 0;
}
在该案例中:
1.左移运算符的重载需要借助友元来实现自定义数据类型
2.cout的类型为ostream
自增++重载
自增++的实现需要基于左移重载的实现:
#include <iostream>
using namespace std;
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger (int num)
{
mnum = num;
}
//MyInteger&保证每次操作的对象为同一个
MyInteger& operator++()
{
mnum++;
return *this;
}
//函数重载,同一作用域下,形参数量,顺序,以及类型
//int 代表占位参数,用来区分前置后置递增
MyInteger& operator++(int)
{
MyInteger temp = *this;
mnum++;
return temp;
}
private :
int mnum;
};
ostream& operator<<(ostream& cout,MyInteger myint)
{
cout << myint.mnum ;
//保证连续操作的对象为同一个
return (cout);
}
void test()
{
MyInteger myint(0),myint1(1);
cout << ++(++myint) << endl;
cout << myint << endl;
cout << ++(++myint1) << endl;
cout << myint1 << endl;
}
void test02()
{
MyInteger myint1(2);
cout << ++(++myint1) << endl;
cout << myint1 << endl;
}
int main()
{
test();
test02();
system("pause");
return 0;
}
在该案例中,
1.MyInteger&保证每次操作的对象为同一个
2.int代表占位,用来区分前置后置递增。
3.前置递增,先进行++操作,随后进行返回。
mnum++;
return *this;
4.后置递增,先将当前值进行记录,然后进行++操作,最后将记录的值进行返回
MyInteger temp = *this;
mnum++;
return temp;