我有以下人为的示例(来自真实代码):
template <class T>
class Base {
public:
Base(int a):x(a) {}
Base(Base<T> * &other) { }
virtual ~Base() {}
private:
int x;
};
template <class T>
class Derived:public Base<T>{
public:
Derived(int x):Base<T>(x) {}
Derived(Derived<T>* &other): Base<T>(other) {}
};
int main() {
Derived<int> *x=new Derived<int>(1);
Derived<int> y(x);
}
当我尝试编译它时,我得到:
1X.cc: In constructor ‘Derived<T>::Derived(Derived<T>*&) [with T = int]’:
1X.cc:27: instantiated from here
1X.cc:20: error: invalid conversion from ‘Derived<int>*’ to ‘int’
1X.cc:20: error: initializing argument 1 of ‘Base<T>::Base(int) [with T = int]’
1) 显然 gcc 被构造函数弄糊涂了。如果我从构造函数中删除引用,那么代码就会编译。所以我的假设是向上转换指针引用出了点问题。有人能告诉我这里发生了什么吗?
2)一个稍微不相关的问题。如果我要在构造函数中做一些可怕的事情,比如“删除其他”(请耐心等待),当有人向我传递一个指向堆栈上某物的指针时会发生什么?
E.g. Derived<int> x(2);
Derived<int> y(x);
where
Derived(Derived<T>*& other) { delete other;}
如何确保该指针合法地指向堆上的某些东西?