我有
Tree<std:string> tree;
现在
new Tree<std:string>;
导致指针, 如何将树的地址更改为由new生成的指针的地址?
答案 0 :(得分:5)
使C ++代码看起来像Java是一个坏主意,这两种语言非常不同。
也就是说,在C ++中,运算符new
返回指向已分配对象的指针。
Tree<std::string> * tree = new Tree<std::string>;
tree->do_something();
您还可以绑定对象的引用。
Tree<std::string> & tree2 = *tree;
tree.do_something();
我敦促你不要这样做。写->
代替.
并不困难。
答案 1 :(得分:4)
我觉得你在这里有点困惑。 在C ++中,当您声明一个对象时,会自动调用构造函数,您不需要新建它。做完之后:
Tree<std:string> tree;
您已经可以访问树,并且已经调用了它的构造函数。
它已经是一个构造的对象。如果你想拥有一个指针,并在堆中构造一个对象,而不是堆栈,你需要这样做,
Tree<std:string> *tree;
tree = new Tree<std:string>;
然后使用* tree访问树。 如果向构造函数添加printf语句,可以看到它是如何工作的。
答案 2 :(得分:2)
你做不到。使用Tree<std:string> tree;
创建对象会在内存中的某个特定位置创建树,但您无法更改它。
也许你想要的是让树成为指针Tree<std:string> *tree = 0;
。当你这样做时,树不再是一个对象而是一个指针。然后,您可以通过分配新tree = new Tree<std::string>;
答案 3 :(得分:0)
我还建议阅读Alok的评论,并考虑一下。
这里有一些从自动存储过渡到动态存储的替代方法示例。它使用std::vector
等同于您的Tree
类,但它可以是您喜欢的任何类型。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> v(3);
v[0] = "abc";
v[1] = "def";
v[2] = "ghi";
// option #1 - make a copy
{
vector<string>* pv = new vector<string>(v);
std::copy(pv->begin(), pv->end(), std::ostream_iterator<string>(cout, ", "));
delete pv;
}
cout << endl;
// option #2 - move content from original vector to new'ed one
{
vector<string>* pv = new vector<string>();
pv->swap(v);
std::copy(pv->begin(), pv->end(), std::ostream_iterator<string>(cout, ", "));
delete pv;
}
}