简体   繁体   中英

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. 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.

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. That's why casting the BaseObject back to jbyte is no longer possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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