.net c ++ / cli获取指针的内容

时间:2012-01-05 07:13:18

标签: c++ .net pointers c++-cli

我想在c ++ / cli

中学习以下代码的相应代码
People* my_people = new People("name","lname");
People* second_people;
&second_people = &my_people;

//

People^  my_people = gcnew People("name","lname");
People^ second_people;
// what is this line?

实际上我想将my_people的内容分配给second_people。 因此,当我更改my_people的内容时,second_people的内容必须相同。

2 个答案:

答案 0 :(得分:1)

首先,你的第一段代码没有编译,没有意义。 second_people并未指向任何对象,因此您无法将副本分配给不存在的对象。相反,你应该写

People* my_people = new People("name","lname");
People* second_people = new People(*my_people);

假设您已经实现了Rule of Three

现在回到这个问题。对于C ++ / Cli,您还应该实现复制构造函数和赋值运算符,如

People(const People % other) { ... }
const People % operator = (const People % other) { ... ; return *this;}

如果我们将此问题应用于您的问题:

People^  my_people = gcnew People("name","lname");
People^ second_people = gcnew People(*my_people);

答案 1 :(得分:0)

您可以像这样my_people分配second_peoplesecond_people = my_people。这是因为你正在使用参考文献。

以下是一些完整的例子:

using namespace System;

ref class People {
public:
    String^ name;
};

int main(array<System::String ^> ^args)
{
    People^ myPeople = gcnew People();
    People^ secondPeople = myPeople;
    myPeople->name = gcnew String(L"My People");
    Console::WriteLine(secondPeople->name);
    return 0;
}

它会打印My People