C++ using新用法、类成员指针

泪湿孤枕 提交于 2020-02-07 01:39:01

一、using新用法

template.h

#pragma once
#include <iostream>
#include <map>

template <typename wt>
struct map_s
{
	typedef std::map<std::string, wt> type;
};

//C++11
template <typename T>
using str_map_t = std::map<std::string, T>;

int RealFunc(int i, int j)
{
	return i + j;
}
typedef int(*FuncType)(int, int);
using FuncType = int(*)(int, int);

typedef  unsigned int uint_t;
using uint_t = unsigned int;

main.cpp

#include <iostream>
#include "template.h"
using namespace std;

int main()
{
    map_s<int>::type map1;
    map1.insert({ "first", 1 });
    str_map_t<int> map2;
    map1.insert({ "second", 1 });

    FuncType funcType = RealFunc;
    funcType(1, 2);
}

using比typedef在定义类型上更人性化。

 

二、类成员指针

#include <iostream>
#include "template.h"
using namespace std;

class CT 
{
public:
	void ptfunc(int tmpValue) { cout << "normal funtiob" << endl; }
	void ptvirtualfunc(int tmpValue) { cout << "virtual funtiob" << endl; }
	static void ptstaticfunc(int tmpValue) { cout << "static funtiob" << endl; }
};

int main()
{
	void (CT::*myctFt)(int);
	myctFt = &CT::ptfunc;//只是定义了函数指针,只是个地址
	CT ct;
	(ct.*myctFt)(100);//只有有类对象后,才能调用

	void (CT::*myctVirtualFt)(int);
	myctVirtualFt = &CT::ptvirtualfunc;
	(ct.*myctFt)(200);

	void (*myctStaticFt)(int) = &CT::ptstaticfunc;//静态方法无需类对象
	myctStaticFt(300);
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!