65,186
社区成员




#include<iostream>
#include<typeindex>
using namespace std;
class Any{
public:
template<typename T>
Any(T t) :myBase(new Data<T>(t)) { }
template<typename T>
T get() {
return dynamic_cast<Data<T>*>(myBase.get())->value;;
}
private:
class Base {
public:
virtual ~Base() {}
};
template <typename T>
class Data :public Base {
public:
typedef T value_type; //传不出去。
Data(T t) {
value = t;
}
T value;
};
unique_ptr<Base> myBase;
type_index index(void); //我想能否根据构造Data类的时候通过修改此变量,可以将函数类型传回来,但是无法用做类型名(!auto,!decltyoe),求告知方法=.=
};
int main() {
Any a(string("s123")), b = 1, c = 12.0;
cout << a.get<string>() << endl; /*调用get函数必须要填写模板参数,我感觉这样大大降低了any的作用*/
cout << b.get<int>() << endl; /*我想能否在构造的时候就确认参数的类型,保证get调用的时候不需要使用模板参数*/
cout << c.get<double>();
return 0;
}
#include <iostream>
#include <typeinfo>
using namespace std;
class ClsA
{
public:
ClsA(){_length=1;_hieght=1;}
ClsA(int len, int high)
:_length(len),_hieght(high) {}
//virtual void who_am_i()const{ cout <<typeid(this).name() << " in " << "ClsA"<< "\r\n"<<_length <<", " << _hieght <<endl;}
int _length;
int _hieght;
};
class ClsB:public ClsA
{
public:
ClsB(){_length=1;_hieght=1; _width=1;}
ClsB(int len, int high, int width)
:ClsA(len,high),_width(width){}
//virtual void who_am_i()const{ cout <<typeid(this).name() << " in " << "ClsB" << "\r\n" << _length << ", " << _hieght << ", " << _width << endl;}
int _width;
};
class ClsC:public ClsA
{
};
int main()
{
ClsA clsA;
ClsB clsB(1,2,3);
ClsC clsC;
int a;
//clsA.who_am_i();
//clsB.who_am_i();
clsA = clsB;
//clsA.who_am_i();
ClsA *pA;
pA = &clsB;
//pA->who_am_i();
cout <<"pA类型" <<typeid(*pA).name() << endl;
return 0;
}
#include <iostream>
#include <typeinfo>
using namespace std;
class ClsA
{
public:
ClsA(){_length=1;_hieght=1;}
ClsA(int len, int high)
:_length(len),_hieght(high) {}
virtual void who_am_i()const{ cout <<typeid(this).name() << " in " << "ClsA"<< "\r\n"<<_length <<", " << _hieght <<endl;}
int _length;
int _hieght;
};
class ClsB:public ClsA
{
public:
ClsB(){_length=1;_hieght=1; _width=1;}
ClsB(int len, int high, int width)
:ClsA(len,high),_width(width){}
virtual void who_am_i()const{ cout <<typeid(this).name() << " in " << "ClsB" << "\r\n" << _length << ", " << _hieght << ", " << _width << endl;}
int _width;
};
int main()
{
ClsA clsA;
ClsB clsB(1,2,3);
clsA.who_am_i();
clsB.who_am_i();
clsA = clsB;
clsA.who_am_i();
ClsA *pA;
pA = &clsB;
pA->who_am_i();
cout <<"pA类型" <<typeid(*pA).name() << endl;
return 0;
}