【问题标题】:Copy constructor calling copy constructor of another class复制构造函数调用另一个类的复制构造函数
【发布时间】:2015-12-22 20:12:03
【问题描述】:

我想知道,如果我这样做,我可以在类B 的复制构造函数中调用模板类A 的复制构造函数,这两个类不在同一个文件中。

template<typename T> class A: public AP<T>
{
    public:
        A();
        A(const A&);
        ~A();
};



#include "A"
class B: public BP
{
    private:
       A<int> Amember;
    public:
        B();
        B(const B&);
        ~B();
};

谢谢:)

【问题讨论】:

  • 需要更多信息——你想复制什么? B 是否有 A 类型成员? BP 类型是否与 AP 有某种关联?
  • “都继承了 AP 和 BP 类”——据我们所见,它们没有。一个继承自AP,另一个继承自BP。无论如何,B 没有/不是A
  • 哦,是的,抱歉 LogicStuff 我表达得不好,我要给你加一些 inofs
  • 你不能在B 中有A&lt;T&gt; Amember;,因为它不是一个类模板(有T 作为参数)。要么将其设为 1,要么指定 T - A&lt;int&gt; Amember;
  • 是的,实际上已经是这样了,抱歉我做例子时弄错了:s

标签: c++ templates constructor


【解决方案1】:

如果我理解这个问题,我认为您在 B 类的构造函数中的可选初始化列表之后。如果您想调用默认构造函数或复制构造函数,这无关紧要。在构造函数的定义中,你可以放一个冒号和每个成员变量应该如何初始化的列表。即,应该调用哪个构造函数。

#include <iostream>

using namespace std;

class A{
  public:
   A(){cout<<__PRETTY_FUNCTION__<<endl;}
   A(int i){cout<<__PRETTY_FUNCTION__<<" "<<i<<endl; data = i;}
   A(const A& a){cout<<__PRETTY_FUNCTION__<<endl; data = a.data;}
  private:
   int data;
};

class B{
  public:
   B() : a(){}
   B(int i) : a(i){}
   B(const B& b) : a(b.a) {}
  private:
   A a;
};

int main(){
  B b1; // default constructor

  B b2(5); // integer constructor

  B b3(b2); // copy constructor

}

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 2015-07-02
    • 2013-06-23
    • 2012-02-28
    • 1970-01-01
    • 2013-10-13
    • 2018-10-17
    • 2013-03-06
    • 2017-01-05
    相关资源
    最近更新 更多