我有以下编造的例子(来自真实代码):
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被构造函数搞糊涂了。如果我从构造函数中移除引用(reference),那么代码就可以编译通过。因此,我的假设是指向父类的指针引用(up-casting pointer references)出现了问题。有人能告诉我这里到底发生了什么吗?
2) 一个稍微不相关的问题。假如我在构造函数中做了一些可怕的事情,比如"delete other" (请包容我),那么当有人把指向栈上某个东西的指针传给我时会发生什么?
E.g. Derived<int> x(2);
Derived<int> y(x);
where
Derived(Derived<T>*& other) { delete other;}
如何确保指针合法地指向堆上的内容?