gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:25:44 24 4
gpt4 key购买 nike

我已经定义了一个堆栈类,其中包含将值压入和弹出到堆栈的方法。

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

堆栈.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++为堆栈类创建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40579676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com