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

Access variable from another class (in C++)

本文关键字:c++ 变量 另一个 访问      更新时间:2023-10-16

这可能是一个非常简单的问题,但是…它开始了。(提前感谢!)

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

source.ccp

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

begin.h

#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
    public:
        void collectdata();
        int test;
};
#endif

begin.cpp

#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
    test = 6;
}

calculation.h

#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
    public:
        void multiply();
};
#endif

calculation.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;
}

简单定义成员函数multiply

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

命名为

int main()
{
    beginclass BEGINOBJECT;
    BEGINOBJECT.collectdata();
    cout << "class " << BEGINOBJECT.test;
    calculationclass SHOWRESULT;
    SHOWRESULT.multiply( BEGINOBJECT );
    system("pause");
    exit(1);
}

在您的代码中beginclass没有显式构造函数,因此将使用隐式定义的默认构造函数,它默认构造所有成员。因此,构建后的beginclass::test要么是0,要么是未初始化的。

你似乎想要避免多次调用beginclass::collectdata()。为此,您需要设置一个标记来记住是否调用了beginclass::collectdata()。返回数据的成员函数首先检查这个标志,如果没有设置标志,则首先调用beginclass::collectdata()

看起来您正在寻找某种延迟计算/缓存技术,即在第一次请求时计算值,然后存储以随后返回它而无需重新计算。

在多线程环境中(使用新的标准线程库)实现此目的的方法是使用std::call_once

如果你是在单线程环境中,并且你只是想从类中获取一个值,请使用getter来获取该值。如果它不是以"惰性"方式计算的,即类立即计算,则可以将该逻辑放入类的构造函数中。

对于"calc_once"的例子:

class calculation_class
{
   std::once_flag flag;
   double value;
   void do_multiply(); 
   double multiply();
public:
   double multiply()
   {
       std::call_once( flag, do_multiply, this );
       return value;
   }
};

如果你想让multiply是const,你需要让do_multiply也是const, value和flag也是可变的