Jou*_*ske 5 c++ templates pointers scope class
假设我有一个具有成员的类模板,该成员pData是一个AxB任意类型的数组T.
template <class T> class X{
public:
int A;
int B;
T** pData;
X(int a,int b);
~X();
void print(); //function which prints pData to screen
};
template<class T>X<T>::X(int a, int b){ //constructor
A = a;
B = b;
pData = new T*[A];
for(int i=0;i<A;i++)
pData[i]= new T[B];
//Fill pData with something of type T
}
int main(){
//...
std::cout<<"Give the primitive type of the array"<<std::endl;
std::cin>>type;
if(type=="int"){
X<int> XArray(a,b);
} else if(type=="char"){
X<char> Xarray(a,b);
} else {
std::cout<<"Not a valid primitive type!";
} // can be many more if statements.
Xarray.print() //this doesn't work, as Xarray is out of scope.
}
Run Code Online (Sandbox Code Playgroud)
由于实例Xarray是在if语句中构造的,所以我无法在其他任何地方使用它.我尝试在if语句之前创建一个指针,但由于指针的类型在那时未知,我没有成功.
处理这类问题的正确方法是什么?
C++ 是一种静态类型语言,这意味着您必须在编译时知道对象的类型。在这种情况下,您将根据用户输入构造对象的类型,因此不可能在运行时知道该类型。
解决此问题的最常见方法是使用动态多态性,其中使用后期绑定通过公共接口调用函数。我们在 C++ 中使用虚函数来实现这一点。例如:
struct IPrintable {
virtual void print() = 0;
};
template<class T>
class X : public IPrintable {
// Same code as you showed above.
};
int main() {
std::cout<<"Give the primitive type of the array"<<std::endl;
std::cin>>type;
std::unique_ptr<IPrintable> XArray;
if(type=="int"){
XArray.reset(new X<int>(a,b));
} else if(type=="char"){
XArray.reset(new X<char>(a,b));
} else {
std::cout<<"Not a valid primitive type!";
} // can be many more if statements.
Xarray->print() // this works now!
}
Run Code Online (Sandbox Code Playgroud)
这解决了超出范围的问题,并允许您使用 XArray 变量的动态类型进行打印。虚拟函数是使这一切成为可能的秘密武器。