C++:在 main() 中使用前向 class 声明的含义

C++: implications in main() of using forward class declarations

我有三个 C++ classes:Position、Employer 和 Person。每个人都有雇主和在该工作中的职位。正如您在下面看到的,我使用前向 class 声明来加入 Employer 和 Position classes 到 Person class.

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

然而,我主要关心的是如何在我的主函数中使用 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;
};

这是来自 main.cpp 的片段:

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

问题是出现编译错误:

error: no matching function for call to 'Person::setPosition(Employer&, Position&)' in main.cpp candidate is: void Person::setPosition(Employer*, Position*)

no known conversion for argument 1 from 'Employer' to 'Employer*'

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

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

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

JLP.setPosition(&StarFleet,&cpt);