【C++知识点】重载
✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:C/C++知识点
📣专栏定位:整理一下 C++ 相关的知识点,供大家学习参考~
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
🎏唠叨唠叨:在这个专栏里我会整理一些琐碎的 C++ 知识点,方便大家作为字典查询~
重载
函数重载
类里面跟普通函数重载类似:
class PrintFunc{
public: void print(int i) {cout << i << endl; } void print(double f) {cout << f << endl;} void print(char c[]) { cout <<c << endl;}
};
运算符重载
运算符重载的本质为函数重载,但有一定的规则需要遵循。
-
重载运算符时,运算符的运算顺序和优先级不变,操作数个数不变。
-
不能创造新的运算符,只能重载C++中已有的运算符,并且规定有6个运算符不能重载,如表所示。
-
运算符重载是针对新类型的实际需求,对原有的运算符进行适当的改造。一般来讲,重载后的运算符的功能应当与运算符的实际意义相符。
运算符重载形式有两种,重载为类的成员函数和重载为类的友元函数。
运算符重载为类的成员函数的一般语法形式为:
函数类型 operator 运算符(形参表)
{ 函数体;
}
运算符重载为类的友元函数的一般语法形式为:
friend 函数类型 operator 运算符(形参表)
{ 函数体;
}
由于运算符种类与数量较多,以以下4大类中的一些符号来讲解。4大类:
- 赋值运算符的重载
- 算术运算符的重载
- 关系运算符的重载
- 其他较为特殊的重载
赋值运算符的重载
class Student{
private:string name;int age;
public:Student(){name = "zs";age = 20;}Student(string name,int age){this->name = name;this->age = age;}void operator=(const Student &t){this->name = t.name;this->age = t.age;}void printInfo(){cout << this->name << " " << this->age <<endl;}
};
int main(){Student s1,s2("王五",30);s2.printInfo();s2 = s1; //使用赋值运算符s2.printInfo();return 0;
}
算术运算符的重载
class complex{
public:complex(){}complex(double r,double i){this->r = r;this->i = i;}complex operator+(complex &c){complex c2;c2.r = this->r + c.r;c2.i = this->i + c.i;return c2; }complex operator-(complex &c){complex c2;c2.r = this->r - c.r;c2.i = this->i - c.i;eturn c2; }void print(){cout << this->r <<" " << this->i <<endl;}
private:double r,i;
};
int main(){complex c1(11,12),c2(10,11),c3,c4;c3 = c1 + c2;c3.print();c4 = c1 - c2;c4.print();
}
关系运算符的重载
class Student{private:string name;int age;public:Student(){}Student(string name,int age){this->name = name;this->age = age;}bool operator>(Student &t){if(this->name > t.name){return true;}else{return false;}}
};
int main(){Student s1("aaa",11),s2("bbb",22);bool b = s2 > s1; //bool b = s1 < s2; bool b = s2 > s1;cout << b << endl;return 0;
}
其他较为特殊的重载
const int SIZE = 5;
class Safearr{private:int arr[SIZE];public:Safearr(){register int i = 0;for(;i<SIZE;i++){arr[i] = i;}}int operator[](int i){if(i >=SIZE){cout << "下标超过最大值" <<endl;return -1;}return arr[i];}
};
int main(){Safearr arr;cout << arr[1] <<endl;cout << arr[100] <<endl;return 0;
}