我需要了解如何在 C++ 中动态分配的字符数组中操作各种索引位置的数据。我正在做一个庸医(队列/堆栈)。我关心的变量是“项目”。
这是 Quack 的类定义:
class Quack
{
public:
static const char YOUR_NAME[]; // used for printing out programmer's name
static const bool PREMIUM_VERSION; // used to designate Regular vs. Premium
Quack(int capacity, int growBy = 0);
// capacity: # of slots in array
// growBy: # of slots to add to array when it grows, 0 means "don't grow"
~Quack(void);
bool pushFront(const char ch); // push an item onto the front
bool pushBack(const char ch); // push an item onto the back
bool popFront(char& ch); // pop an item off the front
bool popBack(char& ch); // pop an item off the back
void rotate(int r); // "rotate" the stored items (see note below)
void reverse(void); // reverse the order of the stored items
int itemCount(void); // return the current number of stored items
void printArray(std::ostream& out) // print contents of array
{
unsigned int ch;
out << "[ ";
for (int i = 0; i < capacity; i++) {
ch = static_cast<unsigned char>(items[i]); // avoid sign extension
if (ch == '-') // print in hex, because using '-' for 0xCD
goto printHex;
else if (ch >= '!' && ch <= '}') // ASCII text character
out << static_cast<char>(ch) << ' ';
else if (ch == 0xCD) // print 0xCD as '-'
out << "- ";
else // print everything else as hex
goto printHex;
continue;
printHex:
out << std::setw(2) << std::setfill('0') << std::hex << ch << ' ';
}
out << ']' << std::endl;
}
private:
char *items;
int nItems;
int capacity;
int growBy;
int *front;
int *back;
public:
friend std::ostream& operator<<(std::ostream& out, Quack *q);
};
现在,这是 Quack 构造函数:
Quack::Quack(int capacity, int growBy) :
capacity(capacity),
growBy(growBy),
nItems(0),
items(new char[capacity]),
front(NULL),
back(NULL)
{
}
我知道 Quack 的每个实例都有一个 char 变量“items”,它是一个指向新字符数组的指针。我不明白的是如何引用数组中的项目。例如,如果我想引用新字符数组的索引位置 0,我是说 items(0) 还是 items[0] ,还是完全不同?
谢谢