【发布时间】:2017-09-07 21:49:36
【问题描述】:
我正在尝试学习 c++,并且必须构建代码来学习类层次结构。它的构造是为了让 A 类和 B 类具有 has-a 关系以及 B 类和 C 类。我需要通过启用 A 的复制构造函数来调用 B 和 C 中的复制构造函数,在我的主文件中复制我的对象,但我不知道怎么做。
#ifndef A_HH
#define A_HH
#include "B.hh"
class A {
public:
A() { std::cout << "Constructor A" << this << std::endl ; }
A(const A&) { std::cout << "Copy Constructor A" << this << std::endl ; }
~A() { std::cout << "Destructor A" << this << std::endl ; }
private:
B b;
} ;
#endif
B类:
#ifndef B_HH
#define B_HH
#include <iostream>
#include "C.hh"
class B {
public:
B() { std::cout << "Constructor B" << this << std::endl ; array = new C[len];}
B(const B& other): array(other.array) { std::cout << "Copy Constructor B" << this << std::endl ;
array = new C[len];
for(int i=0;i<len;i++)
{
C[i] = other.C[i];
}
}
~B() { std::cout << "Destructor B" << this << std::endl ; delete[] array;}
private:
C *array;
static const int len = 12;
} ;
#endif
还有 C 类:
#ifndef C_HH
#define C_HH
#include <iostream>
class C {
public:
C() { std::cout << "Constructor C" << this << std::endl ; }
C(const C&) { std::cout << "Copy Constructor C" << this << std::endl ; }
~C() { std::cout << "Destructor C" << this << std::endl ; }
private:
} ;
#endif
我这样创建两个对象:
#include<iostream>
#include"A.hh"
int main(){
A a;
A a_clone(a);
}
因此在创建a_clone 时,我应该得到复制构造函数的消息,但现在我认为它只是创建一个新对象。
后续问题:我的 B 类实际上看起来像已编辑的 B 类,它必须创建一个动态分配的 C 对象数组。但是这样它仍然不使用复制构造函数。我该如何解决这个问题?
【问题讨论】:
标签: c++ class inheritance copy-constructor