gpt4 book ai didi

c++ - 在 C++ 中使用桥接模式实现 IntStack

转载 作者:行者123 更新时间:2023-11-28 08:22:09 27 4
gpt4 key购买 nike

这道题出自“Thinking in C++”Vol-1, Chapter 5's exercise No.14:

Create a StackOfInt class (a stack that holds ints) using the “Cheshire cat” technique that hides the low-level data structure you use to store the elements in a class called StackImp. Implement two versions of StackImp: one that uses a fixed-length array of int, and one that uses a vector. Have a preset maximum size for the stack so you don’t have to worry about expanding the array in the first version. Note that the StackOfInt.h class doesn’t have to change with StackImp.

这是我创建的头文件 (StackOfInt.h):

#ifndef STACKOFINT_H
#define STACKOFINT_H

class StackOfInt
{
int size;
int curr_idx;
class StackImp;
StackImp* head;
public:
void initialize(int max);
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
#endif

但是,对于实现,我对如何处理数组和 vector 之间的差异感到困惑。这是我到目前为止的想法:

#include "StackOfInt.h"
#include "require.h"
#include <vector>

class StackOfInt::StackImp
{
int arrInt[50];
public:
void initialize()
{
for (int i = 0; i < 50; i++)
{
arrInt[i] = 0;
}
}
};

/*
class StackOfInt::StackImp
{
std::vector<int> vecInt;
}
*/

void StackOfInt::initialize(int max)
{
size = max;
curr_idx = 0;
head = 0;
StackImp* newImp = new StackImp;
newImp->initialize();
}

void StackOfInt::push(void* dat)
{
*(head+curr_idx) = dat;
curr_idx++;
}

void* Stack::peek(int idx)
{
require(head != 0, "Stack empty");
return head[idx];
}

void Stack::cleanup()
{
require(head == 0, "Stack not empty");
} ///:~

我想我走错了路,谁能给我一些关于如何解决这个问题的提示?

最佳答案

本书作者的想法是,除了指向实现类的指针之外,StackOfInt 类不应包含任何其他成员。必要的数据成员,无论是数组+计数变量还是 vector ,都应该是实现类的成员。

所以在标题中,你会有

class StackOfInt {

class StackImp;
StackImp* impl;
public:
void initialize();
void push(int dat);
int peek();
int pop();
void cleanup();
};

在实现文件中,您将拥有实现:

class StackOfInt::StackImp
{
public:
int count;
int array[100];
};

void StackOfInt::initialize()
{
impl = new StackImp;
impl->count = 0;
}

void StackOfInt::push(int dat)
{
impl->array[impl->count++] = dat;
}

//and other methods

编写另一个使用 StackOfImp 类的 cpp 文件。编译项目并运行程序以确保一切正常:)

现在您可以完全重写 StackOfInt 的实现文件以使用 vector 作为基础类型。重新编译项目。请注意,StackOfImp 的用户(测试代码)不必重新编译,因为 header 中没有任何更改

要阅读有关作者称为“柴郡猫”的技术的更多信息:Opaque pointer


请注意,我不明白您对 void 指针的用法。 StackOfInt 应该接受并返回整数。

调用实现指针head 似乎也表明了一些误解。这表示指向对象的指针,该对象实际上包含实现堆栈所需的成员。

关于c++ - 在 C++ 中使用桥接模式实现 IntStack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5410850/

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