"tree"라는 수퍼 클래스를 만들었습니다. 나는이 수업에서 나무를 만들었다. 이제는 생성 된 트리의 루트를 트리의 서브 클래스 인 다른 클래스에 전달하려고합니다. 하지만 그것을 전달하려고하면 하위 클래스가 supercalss 생성자를 호출하고 NULL로 설정합니다.수퍼 클래스에서 C++의 서브 클래스로 값을 전달하는 방법
struct node
{
struct node *left;
struct node *right;
int val;
};
struct node *create(int val)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
};
class tree
{
public:
struct node *root;
tree()
{
root = NULL;
}
void createtree()
{
root = create(5);
}
void preorder()
{
preorderp(root);
}
void preorderp(struct node *p)
{
if(!p) {
return;
}
cout<<p->val<<' ';
preorderp(p->left);
preorderp(p->right);
}
};
이것은 내 트리 클래스의 정의입니다. 이제는 값이 5 인 노드가 하나만있는 트리를 만듭니다. 이제 트리의 하위 클래스에 생성 된 새 루트를 전달하려고합니다.
class treeiterator:public tree
{
struct node *p;
stack<struct node *> s;
public:
treeiterator()
{
p = root;
push(root);
}
bool hasnext();
int next();
private:
void push(struct node *root);
};
먼저 나무 용 개체를 만든 다음 createtree를 만듭니다. 자, treeiterator에 대한 객체를 만들 때 supercalss 생성자가 호출되기 때문에 멤버 p는 NULL로 설정됩니다. 하위 클래스의 수퍼 클래스에서 만든 트리에 어떻게 액세스 할 수 있습니까? 전체 코드 :
#include <bits/stdc++.h>
using namespace std;
struct node
{
struct node *left;
struct node *right;
int val;
};
struct node *create(int val)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->val = val;
temp->left = temp->right = NULL;
return temp;
};
class tree
{
public:
struct node *root;
tree()
{
root = NULL;
}
void createtree()
{
root = create(5);
}
void preorder()
{
preorderp(root);
}
void preorderp(struct node *p)
{
if(!p) {
return;
}
cout<<p->val<<' ';
preorderp(p->left);
preorderp(p->right);
}
};
class treeiterator:public tree
{
struct node *p;
stack<struct node *> s;
public:
treeiterator()
{
p = root;
push(root);
}
bool hasnext();
int next();
private:
void push(struct node *root);
};
void treeiterator::push(struct node *t)
{
while(t) {
s.push(t);
t = t->left;
}
}
bool treeiterator::hasnext()
{
return s.empty()?1:0;
}
int treeiterator::next()
{
struct node *t = s.top();
int val = t->val;
s.pop();
if(t->right) {
push(t->right);
}
return val;
}
int main()
{
tree t;
t.createtree();
t.preorder();
treeiterator it;
while(it.hasnext()) {
cout<<it.next()<<' ';
}
}
왜 C++에서'new' 대신'malloc()'을 사용하고 있습니까? – MikeCAT
필요가 없습니다. 'root'는 공개입니다, 잠깐. 다시 읽으면서 나는 그것을 본다라고 생각한다. 'treeiterator'를 만들 때'tree'가 내장되어 있습니다.'tree'를 만들 필요가 없습니다. 'treeiterator'에서'createtree'를 호출해야하지만, 나는 [RAII를 읽어 보길 권한다] (http://en.cppreference.com/w/cpp/language/raii)와 생성자에서 초기화를 수행하는 것이 좋습니다. – user4581301
@ user4581301 : 자세히 설명해 주시겠습니까? –