Files
python/GESP/Level6/2023-09-XUEZE-7.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

41 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
/*
这行代码报错的原因是:
__data 是 ManyData 类的私有成员private在类外部无法直接访问。在 C++ 中,以双下划线 __ 开头的成员默认是私有的,而且这个变量确实被声明在类的 private 部分。
要访问类的私有成员您需要通过类的公有方法public methods来进行操作。
要修复这个错误,您应该使用类提供的公有方法 at() 来访问数据。把报错的那行代码改成:
*/
class ManyData {
int *__data;
int head, tail, capacity;
public:
ManyData(int cap) {
capacity = cap;
__data = new int[capacity];
head = tail = 0;
}
void push(int val) { __data[tail++] = val; }
int pop() { return __data[--tail]; }
int size() { return tail - head; }
int at(int index) {
if (index >= 0 && index < tail - head) {
return __data[head + index];
}
throw out_of_range("Index out of bounds");
}
};
int main() {
auto myData = new ManyData(100);
myData->push(1);
myData->push(2);
myData->push(3);
myData->push(100);
cout << myData->size() << endl;
cout << myData->pop() << endl;
// cout << myData.__data[0] << endl;
cout << myData->at(0) << endl;
return 0;
}