【问题标题】:Creating a pointer within a class to another object在类中创建指向另一个对象的指针
【发布时间】:2017-04-25 22:54:53
【问题描述】:

请有人帮我纠正以下问题。我正试图围绕如何在新对象中创建指向现有对象的指针。我无法让语法正确并不断出错。

这是我的代码:

class Country
{
    string name; 
public:
    Country (string name)
    {   name = name; 
        cout << "Country has been created" << endl;}

    ~Country()
    {cout << "Country destroyed \n";}

};

class Person
{
    //string name;
    //Date dateOfBirth;
    Country *pCountry; 

public:
    Person(Country *c):
      pCountry(c)
      {}

};




int main()
{
    Country US("United States");
    Person(&US)

    return 0;
}

【问题讨论】:

  • 您可以编辑帖子以包含您遇到的错误吗?
  • 停下来,深呼吸,想想这看起来有多傻。name = name;
  • 您缺少 person 变量的名称,以及声明后的分号 - 除此之外,您在寻找什么?

标签: c++ class pointers object


【解决方案1】:

您是否忘记了 main.cpp 中的内容?

#include <string>
#include <iostream>
using namespace std;

您还需要在主目录中使用分号:

int main()
{
    Country US("United States");
    Person person(&US); // < -- variable name and semicolon missing

    return 0;
}

你也应该改变:

Country (string name)
{
   this->name = name; // <--  assign name to member variable
   ...

或者更好,使用member initializer lists:

Country (string name) : name(name) // <--  assign name to member variable
{
   ...

一般来说,您应该尽量与您的代码格式保持一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-17
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多