【问题标题】:What is the difference between heap member and the reference of one?堆成员和一个引用有什么区别?
【发布时间】:2018-11-18 15:56:06
【问题描述】:

我从一本书中得到了这个复制构造函数,并添加了 cout 来比较值:

Person::Person(const Person& c) {
    m_pName = new string(*(c.m_pName));
    m_Age = c.m_Age;

    cout << m_pName << " " << &m_pName;
}

cout 将输出 2 个不同的地址。我正在阅读的书没有定义没有 & 的 m_pName 本身是什么,它只说 &m_pName 是堆成员地址。没有 & 运算符返回的地址是什么?

编辑:这是类和构造函数:

class Person() {
public:
    Person(const string& name = 0);
    Person(const Person& c);
private:
    string* m_pName;
}

Person::Person(const string& name) {
    m_pName = new string(name);
}

【问题讨论】:

  • 这两个地址是指针所指向的和指针变量本身。
  • 它只说 &m_pName 是堆成员地址这取决于 Person 是否在堆上。
  • m_pName 是一个指向字符串的指针。我认为您可以通过以下行来判断: new string(*(c.m_pName)) 它在哪里被取消引用,但我用一个类和构造函数更新了这个问题以使其更清晰。
  • so &m_pName 是指针的地址,m_pName 是新字符串的地址?
  • 是的,没错。

标签: c++ pointers constructor reference heap-memory


【解决方案1】:

从您提供的 sn-p 看来,m_pName 是指向 string 的指针(可能是指向 std::string),所以 m_pName 不带 & 是该字符串的地址,刚刚分配.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 2016-08-18
    • 2021-05-10
    • 2018-12-23
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多