【问题标题】:C++: implications in main() of using forward class declarationsC++:在 main() 中使用前向类声明的含义
【发布时间】:2016-01-30 21:24:46
【问题描述】:

我有三个 C++ 类:Position、Employer 和 Person。每个人都有一个雇主和一个职位。正如您在下面看到的,我使用前向类声明将 Employer 和 Position 类加入到 Person 类中。

我是前向声明类的新手,但发现 When to use forward declaration 帖子对何时以及如何使用前向声明非常有见地。

但是,我主要关心的是如何在我的 main 函数中使用 setPosition()?

person.h

class Position;
class Employer;

class Person
{
public:
    // other public members
    void setPosition(Employer* newC, Position* newP)
    {
        m_position = newP;
        m_employer = newC;
    }
private:
    // other member variables
    Position* m_position;
    Employer* m_employer;
};

这是 ma​​in.cpp 中的 sn-ps:

#include "employer.h"
#include "person.h"
#include "position.h"

int main()
{
    Employer StarFleet("StarFleet Federation", "space exploration");
    Person JLP("Jean-Luc Picard");
    Position cpt("StarFleet Captain", "Save the world");

    JLP.setPosition(StarFleet,cpt);

    return 0;
}

问题是出现编译错误:

错误:没有匹配函数调用 main.cpp 中的“Person::setPosition(Employer&, Position&)” 候选人是: void Person::setPosition(Employer*, Position*)

没有已知的参数 1 从 'Employer' 到 'Employer*' 的转换

我想知道你将如何在 main() 中使用 setPosition?

我希望我已经说清楚了。如果您需要更多我的代码,请告诉我。

【问题讨论】:

  • 您是否介意告诉我拒绝我的问题的理由,以便我下次提高提问技巧? :) 谢谢

标签: c++ forward-declaration


【解决方案1】:

您的函数参数是指针,但您按值发送变量。您必须使用他们的地址:

JLP.setPosition(&StarFleet,&cpt);

【讨论】:

  • 或者改函数取引用。
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 2021-12-25
  • 1970-01-01
  • 2023-03-16
  • 2013-06-02
  • 2011-12-12
  • 1970-01-01
相关资源
最近更新 更多