C++为堆栈类创建复制构造函数 [英] C++ Creating a copy constructor for stack class

查看:97
本文介绍了C++为堆栈类创建复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在测试程序文件(如下所示)中,在运行该文件后,发生了一次故障&程序崩溃。我知道这是由于函数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
}

这篇关于C++为堆栈类创建复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆