wall 类及其子类以及堆栈本身的实现。 在这里,我将类添加到堆栈中,并使用 isBuildingCorrectly 函数检查是否可以插入下一个对象,但是当我从堆栈访问堆栈上的对象的字段时,会生成错误
接口.h
class Wall: public QObject {
Q_OBJECT
public:
double radiusInside;
double radiusOutside;
double Height;
static int indexNumber;
static double coordinateZ;
QString name = "Wall";
Wall();
virtual ~Wall();
friend double GeneratorMonteCarlo();
};
class Disk : public Wall {
public:
double radiusInside;
double radiusOutside;
Disk(double radiusOutside, double radiusInside); // объявляем конструктор
~Disk(); // объявляем деструктор
//const QString name = "Disk";
int index;
};
class Сylinder : public Wall {
public:
double radiusOutside;
double Height;
Сylinder(double radiusOutside, double height);
~Сylinder();
//const QString name = "Cylinder";
int index;
};
template <typename T>
class Stack {
private:
std::stack<T*> elements;
public:
Stack();
void push(T* value){
elements.push(value);
}
std::size_t Size() {
return elements.size();
}
T* top() const {
return elements.top();
}
void pop() {
elements.pop();
}
bool empty() const {
return elements.empty();
}
~Stack() {
while (!elements.empty()){
delete elements.top();
elements.pop();
}
}
};```
but after the element is added, I cannot access the fields of the object that was added, it throws an exception, but there is a way to output these variables, there will be garbage in them
` QString name = stack.top()->name;
if (name == "Cylinder") {
if ((selected_text == "Cylinder" && val1 == (stack.top()->radiusOutside)) ||
(selected_text == "Disk" && val1 == (stack.top()->radiusOutside)) ||
(selected_text == "Disk" && val2 == (stack.top()->radiusInside))) {
return true;`
您遇到的错误可能是由于使用多重继承以及访问基类的成员时可能导致的歧义造成的。 在您的代码中,Disk 和 Cylinder 都继承自 Wall,并且它们也有自己的数据成员,其名称与 Wall 中的数据成员相同(radiusInside、radiusOutside)。 当您尝试通过基类指针 (stack.top()) 访问这些成员时,C++ 不知道您所指的是哪一个版本的成员,是 Wall 中的版本还是派生类(Disk 或气缸)。