简体   繁体   English

在编写堆栈实现C ++时遇到问题

[英]Having trouble writing stack implementation c++

I am building a programming language interpreter, and I am currently working on writing the stack code. 我正在构建编程语言解释器,并且目前正在编写堆栈代码。 Write now the stack will only hold byte values, but it will be extended to hold other bytes as well. 现在写入,堆栈将仅保存字节值,但也将扩展为容纳其他字节。 At the moment I am having trouble with casting between 'BaseObject' that all my stack objects extend and my jbyte class. 目前,我无法在所有堆栈对象都可以扩展的“ BaseObject”和jbyte类之间进行强制转换。 Here is my current test code. 这是我当前的测试代码。

#include "stdafx.h"
#include <string>
#include <stack>
#include <iostream>
#include <Windows.h>
#include <stack>

using namespace std;

class BaseObject
{
public:
    virtual string getIdentifier(){return "Not Implemented";}
};

class Stack
{
    class jbyte : public BaseObject
    {
    private:
        INT8 byteValue;

    public: 
        jbyte(INT8 value)
        {
            byteValue = value;
        }

        INT8 getValue()
        {
            return byteValue;
        }
    };

private:
    stack<BaseObject> objectStack;

public:
    void pushByte(INT8 byteValue)
    {
        jbyte toPush(byteValue);
        objectStack.push(toPush);
    }

    INT8 popByte()
    {
        if(objectStack.size() == 0)
        {
            cout<<"ERROR: Trying To Pop Value From Empty Stack\nPress Any Key To Continue...";
            _gettch();
            exit(1);
        }
        else
        {
            BaseObject& bo = objectStack.top();
            jbyte& b = dynamic_cast<jbyte&>(bo);
        }
    }
};

int main()
{
    Stack stack;
    stack.pushByte(9);
    stack.popByte();
    while(true);
}

When I try to run this however, I get an Unhandled exception at at 0x75C4C41F in StackTests.exe: Microsoft C++ exception: std::bad_cast at memory location 0x0034F858. 但是,当我尝试运行此命令时, Unhandled exception at at 0x75C4C41F中的0x75C4C41F Unhandled exception at at 0x75C4C41F收到Unhandled exception at at 0x75C4C41F :Microsoft C ++异常:内存位置0x0034F858的std :: bad_cast。

I would like to know how to fix this problem, or if that is difficult, how I could rewrite the stack to work successfully. 我想知道如何解决此问题,或者如果那很困难,我将如何重写堆栈才能成功工作。

When you objectStack.push(toPush) , the jbyte part of toPush is sliced off and only the BaseObject part remains. 当你objectStack.push(toPush)jbyte的一部分toPush被切掉,只有BaseObject部分保持。 That's why casting the BaseObject back to jbyte is no longer possible. 因此,不再可能将jbyte强制BaseObjectjbyte

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM