define用法
只在预处理期间做简单的替换操作,无类型检测
#define long long LL;
typedef用法
给类型定义别名,typedef会在编译阶段对类型进行检查,确保别名的类型与原类型一致。
重定向 FField 类型名为 BaseFieldClass
typedef FField BaseFieldClass;
注意:1. 不能在一个函数定义里面使用typedef
2. 不能用于未具体化或实例化的模板
typedef在c和c++中有些差异
链接:https://blog.youkuaiyun.com/sjxbf/article/details/6330177
using一般有三种用法
1. 为类型声明别名,和typedef一样,但不会做类型检测
#define long long LL;
using LL=long long;
typedef long long LL;
2. 导入命名空间
// 导入整个命名空间到当前作用域
using namespace std;
// 只导入某个变量到当前作用域
using std::cout;
3. 在子类中显式使用父类的成员 (这一点其实可以归纳到2中,因为也是将域中的成员项
显示展示出来)
class Base{
public:
double ave;
};
class Son:private{
public:
using Base::ave;//这里使用基类的成员变量
};
这里显示声明显得有点多余,因为ave的属性为public,对象可以直接使用;当属性为保护
或私有时,显示声明才有意义。
(一般用在当基类以私有或保护方式被继承时,派生类需要通过using声明来显式地访问这
些成员)
PS:也可以显示申明重载时被隐藏的父类函数
class Super
{
public:
virtual void someMethod(); //这是参数的方法
virtual void someMethod(int i); //这是有参数的方法
};
class Sub : public Super
{
public:
using Super::someMethod; // using 显示申明Super::someMethod
virtual void someOtherMethod();
virtual void someMethod();
};
int main()
{
Sub mySub;
mySub.someMethod(7);
}
上面例子中,因为显示声明了using Super::someMethod,子类可以调用带参数的someMethod,如果不用using,将会报错,因为超类的有参数someMethod(int i)的方法被隐蔽,无法调用
typedef和using的区别
唯一的区别是using可用于未具象化模板,typedef只能用于具象化模板。
// 可以编译通过
#include <vector>
using namespace std;
template<typename T>
using myvector=vector<T>;
int main(){
myvector<int> iv;
return 0;
}
// 编译通不过 编译报错error: template declaration of ‘typedef’。
#include <vector>
using namespace std;
template<typename T>
typedef vector<T> myvector;
int main(){
myvector<int> iv;
return 0;
}
//而已经推演过的模板类是可以用typedef设置别名的
#include <vector>
using namespace std;
typedef vector<int> intvector;
int main(){
intvector iv;
return 0;
}