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

时间:2016-11-13 22:46:44

标签: c++ class stack push copy-constructor

我已经定义了一个堆栈类,其中包含用于将值推送到堆栈的方法。

在测试仪文件(如下所示)中,在运行之后,会发生&程序崩溃了。我知道这是由函数f引起的,当两个指针指向内存中的相同位置时会产生错误。如果我在调用函数时注释掉行f(s),则pop&推功能正常工作,输出正确。

为了解决这个错误,我被要求;为此类创建一个复制构造函数来修复上述问题。

我对此并不熟悉,所以在如何做到这一点上会有任何帮助。感谢

主要测试文件

#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];
}

2 个答案:

答案 0 :(得分:1)

这里的复制构造函数很快且很脏:

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
}

答案 1 :(得分:0)

您的复制构造函数应如下所示:

Stack::Stack(const Stack &r) {
    stck_size = r.stck_size;
    stck = new int[stck_size];
    top = r.top;
    memcpy(stck, r.stck, top*sizeof (int));
}
相关问题