如何在c ++中将嵌套类中的类放入?我想用动态分配来做。
以下是代码:
class LZWBinTree{
public:
LZWBinTree():tree (&root){}
~LZWBinTree(){
free(root.oneChild());
free(root.zeroChild());
}
void operator<< (char b){
if (b=='0'){
if (!tree->zeroChild()){
Node *uj=new Node('0');
tree->newZeroChild(uj);
tree=&root;
}
else
tree=tree->zeroChild();
}
else{
if (!tree->oneChild()){
Node *new=new Node('1');
tree->newOneChild(new);
tree=&root;
}
else
tree=tree->oneChild();
}
}
void write(void){
depth=0;
write(&root, std::cout);
}
int getDepth(void);
double getAverage(void);
double getDispersion(void);
friend std::ostream &operator<< (std::ostream &os, LZWBinTree &bf){
bf.write(os);
return os;
}
void write(std::ostream &os){
depth=0;
write(&root, os);
}
private:
class Node{
public:
Node(char b='/'):letter(b), leftZero(0), rightOne(0){};
~Node(){};
Node *zeroChild() const{
return leftZero;
}
Node *oneChild() const{
return rightOne;
}
void newZeroChild(Node *gy){
leftZero=gy;
}
void newOneChild(Node *gy){
rightOne=gy;
}
char getLetter() const{
return letter;
}
private:
char letter;
Node *leftZero;
Node *rightOne;
Node(const Node &);
Node &operator= (const Node &);
};
Node *tree;
int depth, averagesum, averagepiece;
double dispersionsum;
LZWBinTree (const LZWBinTree&);
LZWBinTree& operator= (const LZWBinTree&);
void write(Node *element, std::ostream & os){
if(element!=NULL){
++depth;
write(element->oneChild(), os);
for(int i = 0; i<depth; ++i)
os << "---";
os << element->getLetter() << "(" << depth-1 << ")" << std::endl;
write(element->zeroChild(), os);
--depth;
}
}
void free(Node *element){
if(element!=NULL){
free(element->oneChild());
free(element->zeroChild());
delete element;
}
}
protected:
Node root;
int maxDepth;
double average, dispersion;
void rdepth(Node *element);
void raverage(Node *element);
void rdispersion(Node *element);
};
我希望Node类在LZWBinTree类之外。仅复制和粘贴它还是如何使用动态分配?
答案 0 :(得分:0)
您无法从外部访问节点类,因为它在 LZWBinTree 类中声明为私有。如果要使其可访问,请更改访问修饰符。从:
private:
class Node{ ...
要:
public:
class Node{ ...
一旦这样做,您可以通过它所在的类访问它来创建节点类的实例,如下所示:
LZWBinTree::Node n;
我不太确定动态分配在这种情况下如何帮助你。