开发者

how to change address of variable?

开发者 https://www.devze.com 2022-12-18 20:28 出处:网络
i have Tree<std:string> tree; 开发者_开发技巧 now new Tree<std:string>; leads to a pointer,

i have

Tree<std:string> tree;
开发者_开发技巧

now

new Tree<std:string>;

leads to a pointer, how can i change address of tree to that of pointer generated by new?


Making C++ code look like Java is a bad idea, the two languages are very different.

That said, in C++ operator new returns a pointer to the allocated object.

Tree<std::string> * tree = new Tree<std::string>;
tree->do_something();

You can also bind a reference to your object.

Tree<std::string> & tree2 = *tree;
tree.do_something();

I urge you not to do that. Writing -> instead of . is not that difficult.


I think you're a little confused here. In C++ when you declare an object, the constructor is called automatically, you don't need to new it. After doing:

Tree<std:string> tree;

You can access tree already, and its constructor has been called.

It is already a constructed object. If you want to have a pointer, and construct an object in the heap, and no the stack, you need to do,

Tree<std:string> *tree;
tree  = new Tree<std:string>;

And then use *tree to access tree. You can see how it works if you add a printf statement to the constructor.


You can't. Creating an object using Tree<std:string> tree; creates tree at some specific place in memory and you can't change that.

Perhaps what you want is to make tree be a pointer Tree<std:string> *tree = 0;. When you do that, tree is no longer an object but a pointer. You can then make it point to an object by assigning the return from new tree = new Tree<std::string>;


I'd also recommend to read Alok's comment and think a bit about it.

Here you have examples of alternative approaches of transition from automatic storage to dynamic storage. It uses std::vector as equivalent to your Tree class, but it can be any type you like.

#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;
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号