#include <iostream>
#include <typeinfo>
using namespace std;
class A{
public:
static const char* getMessage(){
return "const hahha";
}
};
class B{
public:
static char* getMessage(){
return "hahha";
}
};
template <class T>
void getMessage()
{
auto message = T::getMessage();
cout<<message<<endl; //auto真的很强大...
}
int main() {
getMessage<A>(); //auto的使用场景之一
getMessage<B>();
//如果不使用上述方法,则只能通过下面两个方法判断
//判断某一个对象到底属于哪一个类别
A s;
B t;
cout<<(typeid(s) == typeid(A))<<endl; //这样来判断某一个对象到底属于哪一个类别
/*
缺点:当存在继承,并且子类指针赋值给父类指针时,此时判断的对象类型为父类型,而不是子类类型
这种办法太low了...
最好的方法是定义虚函数返回类类型
在运行时类型识别,最简单的办法就是所有的类(父类和子类)实现一个虚方法返回类名字,根据返回类名字再利用typeid()进行判断
*/
Func(newcy());
return 0;
}
auto使用注意事项
/*
使用 auto 声明的变量必须马上初始化,以让编译器推断出它的实际类型,并在编译时将
auto 占位符替换为真正的类型
*/
auto i = 10;
const auto *v = &i, u = 6;
cout<<*v<<" is *v"<<endl;
cout<<u<<endl;
auto pi = new auto (1); // new 返回的是int *, malloc 范围的是void *
static auto y = 0.0f;
cout<<*pi<<" is *pi"<<y<<" is y"<<endl;
/*
cv 限定符( cv-qualifier, const 和 volatile 限定符的统称)
*/
auto a = 2;
auto &c = a;
c = 12;
cout<<c<<endl;
右值引用
struct Cy{
Cy(){
cout<<"default"<<endl;
}
Cy(const Cy& cy){
cout<<" copy construct"<<endl;
}
Cy(const Cy&& cy){
cout<<" move construct"<<endl;
}
} ;
Cy newcy(){
Cy b ;
return b;
}
void Func(Cy &&cy){
cout<<" move it here"<<endl; //这就是传说中的右值引用...
}
void Func(Cy &cy){
cout<<" Ref here"<<endl;
}
函数输出结果为:
参考
http://blog.csdn.net/hikaliv/article/details/4541429
后序还要补充,没有写完…