从另一个类访问变量(在c++中)
Access variable from another class (in C++)
这可能是一个非常简单的问题,但是…它开始了。(提前感谢!)
我正在简化代码,所以它是可以理解的。我想使用在另一个类中计算的变量,而不需要再次运行所有内容。
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也是可变的
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用