【问题标题】:How can I pass the result from a function of one class to another?如何将结果从一个类的函数传递给另一个类?
【发布时间】:2022-01-05 12:07:47
【问题描述】:

所以我有 2 个类,即 ForceSolverFrictionContact。我想将变量force 的结果(10)从class ForceSolver 的函数传递给class FrictionContact。例如:

类 ForceSolver

class ForceSolver
{
    public:
        int force;
        int mass = 5;
        int acceleration = 2;

        void solveSystem ();
    };

void ForceSolver::solveSystem()
{
    force = mass * acceleration;
    std::cout << "Force is: " << force;
}

类 FrictionContact

class FrictionContact : public ForceSolver
{
public:
    void printForce();
};

void FrictionContact::printForce()
{
    //print force;
    std::cout << force;
}

ma​​in.cpp

int main()
{
    FrictionContact contact;
   
    contact.printForce();
}

我想知道如何实现。

【问题讨论】:

  • force 不是局部变量,这是一个类成员,在子类中可用。你观察到什么问题?
  • @S.M.你是对的。我忘了删除“*”但这并不能解决问题
  • 在调用printForce之前,需要先调用solveSystem。
  • 您需要在某个地方调用solveSystem() 来计算force,或者在main 中,或者在printForce() 中,或者在父构造函数中。
  • @S.M.我想得到 force 的结果,即 10 并在 FrictionContact 中打印,但我没有得到这个结果

标签: c++ class


【解决方案1】:

我认为在printForce()之前你应该做solveSystem(),否则会打印未初始化的值

class ForceSolver
{
public:
    int force;
    int mass = 5;
    int acceleration = 2;

    void solveSystem ();
};

void ForceSolver::solveSystem()
{
    force = mass * acceleration;
    // std::cout << "Force is: " << force;
}

class FrictionContact : public ForceSolver
{
public:
    void printForce();
};

void FrictionContact::printForce()
{
    // print force;
    std::cout << force;
}

int main()
{
    FrictionContact contact;
    contact.solveSystem();
    contact.printForce();
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 2018-02-05
  • 2011-03-31
相关资源
最近更新 更多