这可能是一个非常简单的问题,但......就在这里。 (先谢谢!)
我正在简化代码,因此可以理解。我想使用在另一个类中计算的变量而不再运行所有内容。
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;
}
答案 0 :(得分:4)
只需将成员函数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);
}
答案 1 :(得分:0)
看起来你正在寻找某种懒惰的评估/缓存技术,即在第一次请求时计算一个值,然后存储它以便随后返回它而不必重新评估。
在多线程环境中,实现此目的的方法(使用新的标准线程库)是使用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并标记为可变。
答案 2 :(得分:0)
在您的代码中beginclass
没有显式构造函数,因此将使用隐式定义的默认构造函数,默认构造所有成员。因此,在构建beginclass::test
之后,0
或未经授权。
您似乎想要的是避免不止一次致电beginclass::collectdata()
。为此,您需要设置一个标记,记住是否已调用beginclass::collectdata()
。返回数据的成员函数然后首先检查此标志,如果未设置标志,则首先调用beginclass::collectdata()
。另请参阅CashCow的答案。