从另一个类访问变量(在 C++ 中)

ram*_*men 0 c++ inheritance class function-definition

这可能是一个非常简单的问题,但是......就这样吧。(提前致谢!)

我正在简化代码,所以它是可以理解的。我想使用在另一个类中计算的变量而无需再次运行所有内容。

源.cc

#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
    beginclass BEGINOBJECT;

    BEGINOBJECT.collectdata();
    cout << "class " << BEGINOBJECT.test;

    calculationclass SHOWRESULT;
    SHOWRESULT.multiply();

    system("pause");
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)

开始.h

#include <iostream>
using namespace std;

#ifndef BEGIN_H
#define BEGIN_H

class beginclass
{
    public:
        void collectdata();
        int test;
};

#endif
Run Code Online (Sandbox Code Playgroud)

开始.cpp

#include <iostream>
#include "begin.h"

void beginclass::collectdata()
{
    test = 6;
}
Run Code Online (Sandbox Code Playgroud)

计算.h

#include <iostream>
#include "begin.h"

#ifndef CALCULATION_H
#define CALCULATION_H

class calculationclass
{
    public:
        void multiply();
};

#endif
Run Code Online (Sandbox Code Playgroud)

计算.cpp

#include <iostream>
#include "begin.h"
#include "calculation.h"

void calculationclass::multiply()
{
    beginclass BEGINOBJECT;
    // BEGINOBJECT.collectdata(); // If I uncomment this it works...
    int abc = BEGINOBJECT.test * 2;
    cout << "\n" << abc << endl;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

只需将成员函数定义multiply

void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
    int abc = BEGINOBJECT.test * 2;
    cout << "\n" << abc << endl;
}
Run Code Online (Sandbox Code Playgroud)

并将其称为

int main()
{
    beginclass BEGINOBJECT;

    BEGINOBJECT.collectdata();
    cout << "class " << BEGINOBJECT.test;

    calculationclass SHOWRESULT;
    SHOWRESULT.multiply( BEGINOBJECT );

    system("pause");
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)