As the topic says I'm very new to c++, but I have some experience with java. To start learning c++ I had the (not very original) idea of making a simple command line calculator. What I'm trying to do is store the numbers and operators in a binary tree.
#include <iostream>
using namespace std;
class Node
{
bool leaf;
double num;
char oper;
Node* pLNode;
Node* pRNode;
public:
Node(double n)
{
num = n;
leaf = true;
pLNode = 0;
pRNode = 0;
}
Node(char o, Node lNode, Node rNode)
{
oper = o;
pLNode = &lNode;
pRNode = &rNode;
leaf = false;
}
bool isLeaf()
{
return leaf;
}
double getNumber()
{
return num;
}
char getOperator()
{
return oper;
}
Node* getLeftNodePointer()
{
return pLNode;
}
Node* getRightNodePointer()
{
return pRNode;
}
//debug function
void dump()
{
cout << endl << "**** Node Dump ****" << endl;
cout << "oper: " << oper << endl;
cout << "num: " << num << endl;
cout << "leaf: " << leaf << endl;
cout << "*******************" << endl << endl;
}
};
class CalcTree
{
Node* pRootNode;
Node* pCurrentNode;
public:
Node* getRootNodePointer()
{
return pRootNode;
}
Node* getCurrentNodePointer()
{
return pCurrentNode;
}
void setRootNode(Node node)
{
pRootNode = &node;
}
void setCurrentNode(Node node)
{
pCurrentNode = &node;
}
double calculateTree()
{
return calculateTree(pRootNode);
}
private:
double calculateTree(Node* nodePointer)
{
if(nodePointer->isLeaf())
{
return nodePointer->getNumber();
}
else
{
Node* leftNodePointer = nodePointer->getLeftNodePointer();
Node* rightNodePointer = nodePointer->getRightNodePointer();
char oper = nodePointer->getOperator();
if(oper == '+')
{
return calculateTree(leftNodePointer) + calculateTree(rightNodePointer);
}
else if(oper == '-')
{
return calculateTree(leftNodePointer) - calculateTree(rightNodePointer);
}
else if(oper == '*')
{
return calculateTree(leftNodePointer) * calculateTree(rightNodePointer);
}
else if(oper == '/')
{
return calculateTree(leftNodePointer) / calculateTree(rightNodePointer);
}
}
}
};
int main(int argc, char* argv[])
{
CalcTree tree;
tree.setRootNode(Node('+', Node(1), Node(534)));
cout << tree.calculateTree() << endl;
return 0;
}
I've got a couple of questions about this code:
This compiles but does not do what's intended. It seems that after tree.setRootNode(Node('+', Node(1), Node(534))); in main, the rightnode is initialized properly but the leftnode isn't. Compiling and running this prints out 534 for me (gcc, freebsd). What is wrong here?
It seems in c++ people prefer to define members of a class outside the class, like
class A { public: void member(); };
A :: member(){std::cout << "Hello world" << std::endl;}
why is that?
I'd very much like some pointers on c++ conventions (naming, indenting etc.)
I'm used to coding java with eclipse. Atm I'm using emacs for learning c++. Can someone advise me on a good (free) c++ ide, or should I stfu and stick with emacs like a real man? :)