I recieve this error when casting:
C:/Mike/Uni/215/A2/tree.cpp:214: cannot dynamic_cast `
currentNode->Node::getData()' (of type `<unknown type>') to type `class
NumericTreeItem*' (source is not a pointer)
TreeItem*' (source is not a pointer)
yet from my examples I see this is how I should be casting
Code:
class TreeItem //an object for a node
{
public:
virtual string stringFormat()=0;
};
class StringTreeItem: public TreeItem
{
private:
string data;
public:
StringTreeItem(string item)
{
data = item;
}
string stringFormat()
{
return data;//already a string
};
};
class NumericTreeItem: public TreeItem
{
public:
virtual string stringFormat()=0;
virtual double number()=0;
};
class IntTreeItem: public NumericTreeItem
{
private:
int data;
public:
IntTreeItem(int number)
{
data = number;
}
string stringFormat()
{
ostrstream S; //an output stringstream
S << data; //just print to the stringstream!
S.put(0); //need to null-terminate the string
//now extract the string from the stringstream
string aString = S.str(); //and you can use aString as you want...
return aString;
}
double number()
{
return (double)data;
}
};
class FloatTreeItem: public NumericTreeItem
{
private:
double data;
public:
FloatTreeItem(double number)
{
data=number;
}
string stringFormat()
{
ostrstream S; //an output stringstream
S << data; //just print to the stringstream!
S.put(0); //need to null-terminate the string
//now extract the string from the stringstream
string aString = S.str(); //and you can use aString as you want...
return aString;
}
double number()
{
return data;
}
};
class Node
{
private:
TreeItem *item;
Node* left;
Node* right;
public:
Node(TreeItem* tree)
{
item = tree;
left=NULL;
right=NULL;
}
Node* getLeft()
{
return left;
}
Node* getRight()
{
return right;
}
void setLeft(Node* left)
{
this->left =left;
}
void setRight(Node* right)
{
this->right = right;
}
TreeItem* getData()
{
return item;
}
void print()
{
}
};
double getSum(double sum,Node* currentNode)
{
//prints entry entry subtree subtree subtree
NumericTreeItem* data = dynamic_cast<NumericTreeItem*>(currentNode->getData);
if(data != NULL) //successful cast
{
//cast to int or double
IntTreeItem* item = dynamic_cast<IntTreeItem*>(data);
if(item !=NULL) //then an int
{
sum = sum+(double)(item->number());
}
else
{
FloatTreeItem* decimal = dynamic_cast<FloatTreeItem*>(data);
if(decimal!=NULL)
sum = sum + (item->number());
}
}
if(currentNode->getLeft()!=NULL)
{
getSum(sum,currentNode->getLeft());
}
if(currentNode->getRight()!=NULL)
{
getSum(sum,currentNode->getRight());
}
return sum;
}
I've included classes and methods involved, although they are in inline order for the file.
Why would I be recieivng that error, since I am casting a "known" Tree Item - I've tried using tree Item but get a similar error.