C++基础知识

1、class和struct的区别

  • class默认成员访问权限是private,而struct中是public;
  • class默认继承方式是private,而struct默认是public;
  • class中有函数,struct中一般没有成员函数。

2、模板

(1)类模板

类模板同意用户为类定义一种模式。使得类中的某些数据成员,默认成员函数的参数,某些成员函数的返回值,能够取任意类型。它的存在不是代表一个详细的类,而是代表一类类。

template.h

template <class T>
class CTest {
private:
    T num;
public:
    CTest();
    ~CTest();

    void Add(T a, T b);
    T Print();
};

template.cpp

在类定义体外定义成员函数时,需在函数体外进行模板声明,且在类名后面加上<T>

#include "template.h"

template <class T>
CTest<T>::CTest()
{
	num = 0;
}

template <class T>
CTest<T>::~CTest()
{
	num = 0;
}

template <class T>
void CTest<T>::Add(T a, T b)
{
	num = a + b;
}

template <class T>
T CTest<T>::Print()
{
	printf("num:%d\n", num);
	return num;
}

(2)模板类

将类模板实例化成一个详细的类,即为模板类。

#include "template.cpp"
int main()
{
    CTest<int> CTest1;
    CTest1.Add(5, 6);
    CTest1.Print();
    return 1;
}

(3)函数模板

能够用来创建一个通用的函数,以支持多种不同的形参。避免重载函数的函数体反复设计。

#include <stdio.h>

template <class T>
T  Decode(T a, T b)
{
    T res = a * 100 + b;
    return res;
}

int main()
{
    double res = Decode<double>(5.4, 4.8);
    printf("res:%f\n", res);
    return 1;
}

(5)函数模板

将函数模板的类型形参实例化的过程。

3、重载

重载是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但它们的形式参数(指参数的个数、类型或者顺序)不同(只有返回值不同不可以重载)。

(1)函数重载

overload.h

#include <string>
using namespace std;

class CTest {
private:
    int num;
public:
    CTest();
    ~CTest();

    void Print(int a);
    void Print(double a);
    void Print(string a);
};

overload.cpp

#include "overload.h"

CTest::CTest()
{
	num = 0;
}

CTest::~CTest()
{
	num = 0;
}

void CTest::Print(int a)
{
	printf("a:%d\n", a * 100);
}
void CTest::Print(double a)
{
	printf("a:%f\n", a * 1000);
}
void CTest::Print(string a)
{
	printf("a:%s\n", a);
}

main.cpp

#include <stdio.h>
#include "overload.h"

int main()
{
    double res = 5.4;
    CTest test2;
    test2.Print(res);
    return 1;
}

(2)运算符重载

重载的运算符是带有特殊名称的函数。函数名是由关键字operator其后要重载的运算符符号构成的。

overload.h

class CTest2 {
private:
    int length;
public:
    CTest2(int b);
    ~CTest2();

    int operator+(CTest2 b);
};

overload.cpp

CTest2::CTest2(int b)
{
	length = b;
}
CTest2::~CTest2()
{

}

int CTest2::operator+(CTest2 b)
{
	int res = b.length + this->length;
	return res;
}

main.cpp

#include <stdio.h>
#include "overload.h"

int main()
{
    CTest2 test1(3);
    CTest2 test2(5);
    int res = test1 + test2;
    return 1;
}
<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值