<分区>
昨天在 C++ 中进行了一整天的错误跟踪后,我将我的问题简化为:
#include <iostream>
class A {
public:
virtual void id() { std::cerr << "This is A\n"; }
};
class A1 : public A {
public:
virtual void id() { std::cerr << "This is A1\n"; }
};
class A2 : public A {
public:
virtual void id() { std::cerr << "This is A2\n"; }
};
template <class T> class jp {
public:
T* ptr;
jp<T> () { ptr = 0; }
jp<T> ( T a ) {
std::cerr << "Recording address\n";
ptr = &a;
}
template <class S> jp<T> ( const jp<S>& s ) {
s.ptr->id();
ptr = s.ptr;
}
/* surely the above template defines "jp<T> ( const jp<T>& s )"
* but the behaviour is different when it is duplicated as follows *
jp<T> ( const jp<T>& s ) {
s.ptr->id();
ptr = s.ptr;
}
*/
};
int main() {
A a;
A1 a1;
jp<A> jpa1(a); // make a jp<A>
jp<A> jpa2(jpa1); // copy constructor
jp<A1> jpa3(a1); // make a jp<A1>
jp<A> jpa4(jpa3); // copy constructor
jp<A1> jpa5(jpa3); // copy constructor
}
我已经定义了一个拷贝构造函数,不是吗?这是
template <class S> jp<T> ( const jp<S>& s )
在 T 等于 S 的特殊情况下。假设这应该有 5 行输出,但我只得到三行:
Recording address
Recording address
This is A1
取消注释重复已经定义的构造函数的部分(但没有模板)给出了我期望的五行输出
Recording address
This is A
Recording address
This is A1
This is A1
有人能解释一下吗?我读过 Stroustrup 好几遍,没想到会这样!关于我没有被告知的其他类似信息,我还应该知道什么?;)
类 A2 的存在只是为了表明 A 可能有许多子类,并且为每个子类重复代码并不是一件小事。
谢谢!