c++ - 为什么 C++ 中的这个复制构造函数不能编译?

标签 c++ constructor compilation copy

我是复制构造函数的新手,所以也许我只是不知道它们是如何工作的,但我不明白为什么这不起作用。以下是构造函数的实现:

Heap::Heap(void){ // New empty Heap with default capacity.
   h_capacity = 10;
   A = new int[h_capacity];
   h_size = 0;
}

Heap::Heap(int c){ // New empty Heap with capacity c.
   A = new int[c];
   h_capacity = c;
   h_size = 0;
}

Heap::Heap(int * B, int s, int c){ // New Heap with capacity c containing first s elements of B.
   A = new int[c];
   h_capacity = c;

   A = new int[h_capacity];

   for (int i = 0; i < s; i++){
      (A[i]) = B[i];
   }

   h_size = s;
}

Heap::Heap( const Heap & H ){ // Copy constructor.
   h_capicity = H->h_capicity;
   h_size = H->h_size;

   A = new int[h_capicity];

   for (int i = 0; i < h_size; i++){
      (A[i]) = H->A[i];
   }

这是头文件:

#include <iostream>
using namespace std;

class Heap{

public:
      // Constructors and Destructor
      Heap();  // New empty Heap with default capacity.
      Heap(int c); // New empty Heap with capacity c.
      Heap(int * B, int s, int c); // New Heap with capacity c containing first s elements from B.
      Heap( const Heap & H ); // Copy constructor.
      ~Heap(); // Destructor.

      // Size and Capacity
      bool empty() {return h_size == 0;}; // True iff Heap is empty.
      int size(){ return h_size ;}; // Current size of Heap.
      int capacity(){ return h_capacity ;}; // Current capacity.

      // Operators
      Heap operator+( const Heap & H ) const; // New Heap with combined contents and capacity of operands.

      // Modifiers
      void insert(int x); // Insert element x.
      int extract_min(); // Remove and return the minimum element.

      // Display
      void display(); // Print a string representation of the heap contents to standard out.

private:
      int* A ; // Array containing heap contents.
      int  h_capacity ; // Max number of elements (= size of A).
      int h_size ; // Current number of elements.

      void trickle_up(int i);// Repairs ordering invariant after changing root.
      void trickle_down(int i);// Repairs ordering invariant after adding a leaf.
      void make_heap();// Restores ordering invariant to entier contents.
};

但是当我编译时我得到:

heap.cpp: In copy constructor ‘Heap::Heap(const Heap&)’:
heap.cpp:34: error: ‘h_capicity’ was not declared in this scope

最佳答案

你拼错了 h_capacity作为h_capicity .

此外,正如其他人所指出的,您需要修复 -> 的用法.编译器会在适当的时候提示。 :)

附言不要忘记定义赋值运算符。

附言标记 Heap(int c); 可能有意义作为explicit , 以防止从 int 进行不需要的隐式转换至 Heap .

关于c++ - 为什么 C++ 中的这个复制构造函数不能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13566206/

相关文章:

c++ - 为什么我不能将这个全局实例化为指针?

c++ - 构造函数初始化

java - Java 如何在 "explicit constructor invocation"期间区分几乎相同的构造函数?

c++ - 如何编译#includes C++代码的C代码?

c++ - 为什么 QCustomPlot 在绘制大数据时速度太慢?

c++ - OpenGL - 纹理加载不正确

c++ - 在 C++ 中解压缩目录

Linux:如何获取刚刚从构造函数加载的共享对象的全名?

c# - C#编译器的泛型、继承和失败的方法解析

在命令提示符下找不到exe