C++ 使用默认的复制构造函数,即使用户使用模板定义了一个?

标签 c++

<分区>

昨天在 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 可能有许多子类,并且为每个子类重复代码并不是一件小事。

谢谢!

最佳答案

I have defined a copy constructor haven't I?

不,你没有。复制构造函数永远不是模板。您定义的是一个构造函数,它允许您构造一个 jp<T>来自任何 jp<S> (即(jp<int> 来自 jp<double>)

因为你实际上没有定义一个复制构造函数,编译器会为你创建一个,因为它在你永远看不到的重载决议中获胜

template <class S> jp<T> ( const jp<S>& s ) 

接到电话。

关于C++ 使用默认的复制构造函数,即使用户使用模板定义了一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49887161/

相关文章:

c++ - 如何使用函数指针从其内存地址调用成员函数?

c++ - 如何限制 "e"之前的小数位?

c++ - 使用 C++ 的 STL 列表 ....传递列表指针数组

c++ - 如何识别安装程序类型?

c++ - 警告 : 'auto' type specifier is a C++11 extension

c++ - clang vs gcc - 优化包括 operator new

c++ - C++ map 中的 Char 二维数组

c++ - 当函数返回类型为 bool 时,为什么不能在 C++14 中返回共享指针?

c++ - 在没有循环的情况下将函数应用于特征矩阵中的所有元素

c++ - 如何仅在某些时候生成编译器警告?