C++为堆栈类创建复制构造函数

2022-07-03 00:00:00 class stack c++ push copy-constructor

我定义了一个堆栈类,其中包含用于将值推入和弹出堆栈的方法。

在测试程序文件(如下所示)中,在运行该文件后,发生了一次故障&程序崩溃。我知道这是由于函数f造成的,该函数在两个指针指向内存中的同一位置时会产生错误。如果我在调用函数时注释掉f(S)行,弹出和推入函数就能正常工作,输出也是正确的。

若要修复此错误,我被要求为此类创建复制构造函数以修复上述问题。

我对此不是很熟悉,因此如果有任何帮助,我将不胜感激。谢谢

主测试文件

#include "Stack.h"
#include <iostream>
#include <string>
using namespace std;

void f(Stack &a) {
    Stack b = a;
}


int main() {

    Stack s(2); //declare a stack object s which can store 2 ints
    s.push(4); //add int 4 into stack s

    //s = [4]
    s.push(13); //add int 13 into stack s
    //s = [4,13]

    f(s); //calls the function f which takes in parameter Stack a , and sets Stack b = to it.
    //error here - as 2 pointers point to the same location in memory !
    cout << s.pop() << endl; //print out top element(most recently pushed) element.
    //so should output 13
    return 0;
}

表头文件编码

#ifndef STACK_H
#define STACK_H

class Stack {
public:
    //constructor
    Stack(int size);

    //destructor
    ~Stack();

    //public members (data & functions)
    void push(int i);
    int pop();

private:
    //private members (data & functions)
    int stck_size;
    int* stck;
    int top;
};

#endif

Stack.cpp代码

#include "Stack.h"
#include <iostream>
#include <string>
using namespace std;

Stack::Stack(int size){
    stck_size = size;
    stck = new int[stck_size];
    top = 0;
}
Stack::~Stack() {
    delete[] stck;
}
void Stack::push(int i) {
    if (top == stck_size) {
        cout << "Stack overflow." << endl;
        return;
    }
    stck[top++] = i;
}

int Stack::pop() {
    if (top == 0) {
        cout << "Stack underflow." << endl;
        return 0;
    }
    top--; //decrement top so it points to the last element istead of the empty space at the top.
    return stck[top];
}

解决方案

这里的复制构造函数非常快,而且很脏:

Stack::Stack(const Stack & src): 
    stck_size(src.stack_size),
    stck(new int[stck_size]),
    top(src.top) //Member Initializer List
{
    // copy source's stack into this one. Could also use std::copy.
    // avoid stuff like memcpy. It works here, but not with anything more 
    // complicated. memcpy is a habit it's just best not to get into
    for (int index = 0; index < top; index++)
    {
        stck[index] = src.stck[index];
    }
}

现在您有了一个复制构造函数,您可能仍然搞砸了,因为Rule of Three has not been satisfied.您需要operator=。这很容易,因为复制结构和the copy and swap idiom makes it easy.

基本形式:

TYPE& TYPE::operator=(TYPE rhs) //the object to be copied is passed by value
                                // the copy constructor makes the copy for us.
{
  swap(rhs); // need to implement a swap method. You probably need one 
             //for sorting anyway, so no loss.
  return *this; // return reference to new object
}

相关文章