如何从我的Node指针数组中访问元素?底部的cout返回一个地址" 0xb7738ff4"。即使我创建了一个构造函数并将每个元素设置为NULL,我也无法在以后修改它们。
#include <iostream>
using namespace std;
class Node
{
public:
char character;
};
class Tree
{
public:
Node* nodes[26];
};
int main() {
Tree t;
//t.nodes[0]->character = 'a';
cout << "\"" << (t.nodes[0]) << "\"";
}
答案 0 :(得分:2)
t.nodes[0]
正在返回Node*
指针。您将该指针按原样传递给cout
,这就是为什么它正在打印一个内存地址(以及随机的那个,因为您没有初始化该数组)。如果要打印节点的character
,则必须取消引用Node*
指针,就像注释掉的代码一样(这是正确的方法):
t.nodes[0]->character
您必须确保nodes[0]
返回指向真实Node
对象的有效指针,以便开始:
Tree t;
t.nodes[0] = new Node; // <-- here
t.nodes[0]->character = 'a';
std::cout << "\"" << t.nodes[0]->character << "\"" << std::endl;
完成使用后,不要忘记delete
节点。 Tree
应该有一个析构函数来释放它拥有的节点。
尝试更像这样的事情:
#include <iostream>
#include <stdexcept>
class Node
{
public:
char character;
Node(char c = 0);
};
class Tree
{
private:
Node* nodes[26];
int count;
public:
Tree();
~Tree();
Node* add(char c);
Node* get(int idx);
};
Node::Node(char c)
: character(c)
{
}
Tree::Tree()
: count(0)
{
for (int i = 0; i < 26; ++i)
nodes[i] = NULL;
}
Tree::~Tree()
{
for (int i = 0; i < count; ++i)
delete nodes[i];
}
Node* Tree::add(char c)
{
if (count == 26)
throw std::runtime_error("nodes array is at its max capacity");
Node *node = new Node(c);
nodes[count++] = node;
return node;
}
Node* Tree::get(int idx)
{
if ((idx < 0) || (idx >= count))
throw std::out_of_range("invalid index");
return nodes[idx];
}
int main()
{
Tree t;
t.add('a');
std::cout << "\"" << t.get(0)->character << "\"" << std::endl;
}
话虽如此,您应该使用std::list
或std::forward_list
而不是编写自己的树类:
#include <list>
int main()
{
std::list<char> l;
l.push_back('a');
std::cout << "\"" << l.front() << "\"" << std::endl;
}
或者:
#include <list>
class Node
{
public:
char character;
// other things here...
Node(char c = 0);
Node(const Node &src);
Node& operator=(const Node &rhs);
};
Node::Node(char c)
: character(c)
{
}
Node::Node(const Node &src)
: character(src.character)
{
}
Node& Node::operator=(const Node &rhs)
{
character = src.character;
return *this;
}
int main()
{
std::list<Node> l;
l.push_back('a');
std::cout << "\"" << l.front().character << "\"" << std::endl;
}