C++学习足记1(一)

2018-8-2

1、引用

  • 引用是被引用对象的别名,对引用的操作就是对变量的操作
  • 举个/栗子
#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    int a =90;
    int *p = &a;
    cout << "a=" << a << " *p" << *p << endl;
    //定义一个a的引用,此处必须强制初始化
    int &ui = a;
    cout << "a=" << a << " ui" << ui <<endl;
    int b = 99;
    //在此处并没有将ref作为b的引用,只是将b的值赋值给了ref引用的对象,即a
    ui = b;
    cout << "a=" << a << " ui" << ui <<endl;
    return 0;
}

程序输出为:
a = 90 ref = 90
a = 99 ref = 99

2、函数重载

  • 举个栗子
#include <iostream>

using namespace std;

int myadd (const int a, const int b){
    return a+b;
}
float myadd (const float a, const float b){
    return a+b;
}
double myadd (const double a, const double b){
    return a+b;
}
string myadd (const string a, const string b){
    return a+b;
}
int main(int argc, char const *argv[])
{
    int a = 1 , b = 2;
    cout<< myadd(a,b) ; 
    return 0;
}
如上有四个函数名相同的函数,他们的形式参数不一样,称为函数的重载,在调用时会根据传入的数据类型自动调用对应的函数。

3、函数模板

#include <iostream>

using namespace std;
template <tempname U>
U myadd (U a, U b){
    return a+b;
}
in(int argc, char const *argv[])
{
    int a = 1 , b = 2;
    cout<< myadd(a,b) ; 
    return 0;
}
使用模板时,不会调用模板函数,而是根据传入参数的类型自动生成新函数,在上面的函数中,他会实例化 U add
即实际执行的函数是 int myadd(int a, int b){ …… }
如果需要传入两个不同类型的函数时,可以这么写
template <tempname U, tempname M>
U add(U a, M b){
    …… 
}

静态成员变量

static 修饰的变量称为静态成员变量
静态成员变量不可以在类中定义,必须在类外定义

猜你喜欢

转载自blog.csdn.net/weixin_40273809/article/details/81357804