C/C++基础知识(三)——单例、重载、模板

2019-10-12  本文已影响0人  王志强_9380

单例对象和操作符重载

studentinstance.h

#pragma once
class StudentInstance
{
private:
    
    static StudentInstance* instance;
    StudentInstance() {
    };
public:
    static StudentInstance* getInstance();

};
studentinstance.cpp

#include "studentinstance.h"

StudentInstance* StudentInstance::instance = 0;

StudentInstance* StudentInstance::getInstance() {
    if (!instance) {
        instance = new StudentInstance();
    }
    return instance;
}

单例调用

StudentInstance* studentInstance = StudentInstance::getInstance();

注意:指针声明的时候一定要初始化,.h里面声明的构造函数也要实现,否则会报错

操作符重载:

#pragma once
class OperatorAdd
{
public:
    int  i;
    OperatorAdd operator+(const OperatorAdd& p) {
        OperatorAdd temp;
        temp.i = this->i + p.i;
        return temp;
    };
};

使用关键字operator把加号重载了,调用的时候,类可以直接相加

OperatorAdd add1;
add1.i = 1;
OperatorAdd add2;
add2.i = 3;
OperatorAdd add3;
add3 = add1 + add2;

类模板和函数模板

类似于java中的泛型

//类模板
template <class T, class E>

class tempTest {
public:
    T addClassTemp(T t, E e) {
        return t + e;
    }

    //函数模板
    template <typename Q>
    Q addFuncTemp(Q i, Q j) {
        return i + j;
    }
};

执行

tempTest<float, int> tempt;
float tempclass1 = tempt.addClassTemp(3, 2.12f);
int tempclass2 = tempt.addClassTemp(3, 2.12f);
float tempclass3 = tempt.addClassTemp(2.12f, 3);
int tempclass4 = tempt.addClassTemp(2.12f, 3);
float tempfunc = tempt.addFuncTemp(2.12f, 3.56f);
std::cout << tempclass1 << std::endl;
std::cout << tempclass2 << std::endl;
std::cout << tempclass3 << std::endl;
std::cout << tempclass4 << std::endl;
std::cout << tempfunc << std::endl;

执行结果:
5
5
5.12
5
5.68

上一篇下一篇

猜你喜欢

热点阅读