函数重载,可以让函数名相同,提高复用性
#include <iostream> using namespace std; /* 重载需要满足的条件: 1.发生在同一作用域下 2.函数名称相同 3.函数参数类型、个数、顺序不同 */ void func() { cout <<"func()" << endl; } void func(int a) { cout <<"func(int a)" << endl; } void func(double a) { cout <<"func(double a)" << endl; } void func(int a, double b) { cout <<"func(int a, double b)" << endl; } void func(double a, int b) { cout <<"func(double a, int b)" << endl; } /*注意 函数的返回值不可以作为函数重载的条件,如下,是不被允许的 int func(double a, int b) { cout <<"func(double a, int b)" << endl; } */ int main() { func(); func(10); func(3.14); func(3,3.14); func(3.14,3); return 0; }
函数重载的注意事项
1.引用作为重载条件
2.函数重载碰到函数默认参数
#include <iostream> using namespace std; /* 重载注意事项: 1.引用作为重载条件 */ void func(int &a) { // int &a = 10; 不合法 cout << "func(int &a)" << endl; } void func(const int &a) { // const int &a = 10; 合法 cout << "func(const int &a)" << endl; } /* 重载注意事项: 2.函数重载碰到函数默认参数 */ void func2(int a, int b = 10) { cout << "func2(int a, int b)" << endl; } void func2(int a) { cout << "func2(int a)" << endl } int main() { int a = 10; func(a); //调用无const func(10); //调用有const // func2(10); 当函数重载碰到默认参数,出现二义性报错,尽量避免默认参数的情况 return 0; }
C++三大特性:封装、继承、多态
封装
封装的意义:
1.将属性和行为作为一个整体,表现生活中的事物
2.将属性和行为加以权限控制
class 类名 { 访问权限: 属性 / 行为};
设计一个圆类,求圆的周长
#include <iostream> using namespace std; const double PI = 3.14; class Circle { //访问权限 public: //属性 int r; //行为 double calculateD() { return 2 * PI * r; } }; int main() { // 通过圆类,创建具体的圆(对象) // 实例化,通过一个类创建一个对象的过程 Circle c1; //给圆对象的属性进行赋值 c1.r = 21; cout << "圆的周长为:" << c1.calculateD() <<endl; return 0; }