为什么当我使用一个单独类的int时,它会给我随机数
Why is it that when I use an int from a separate class, it gives me random numbers?
我对编码相对较新,到目前为止我知道Java和C++的基础知识,但我正在尝试更多地组织我的代码,并稍微加快编译时间。到目前为止,我只知道如何使用其他类的函数。我正在自学一切,所以如果有人能用我发布的代码给我看一个例子,那就太完美了。请随意解释,就像你在和孩子说话一样,因为这些头文件让我很困惑。
test.h:
#pragma once
class test
{
public:
//functions
test();
void part2();
//variables
int varA;
};
test.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "test.h"
int varA = 10;
test::test()
{
cout << "this is the test main function" << endl;
}
void test::part2(){
cout << "you got to part 2, also, Variable A is " << varA << " when it's in test.cpp" << endl;
}
控制台应用程序1
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
#include "test.h"
int main()
{
test objectA;
objectA.part2();
cout << "variable A is " << objectA.varA << "when it's in CA1.cpp" << endl;
system("pause");
return 0;
}
这是控制台的输出
this is the test main funtion
you got to part 2, also, Variable A is -858993460 when it's in CA1.cpp
variable A is -858993460 in CA1.cpp
Press any key to continue . . .
编辑:那么我只能得到我在test::test构造函数的头中声明的varA吗?我用这种方法进行了测试,结果是有效的,它确实返回了10。然而,如果我想在头/类中,在构造函数之外的另一个函数中使用相同的变量,它会再次给我带来混乱。我似乎唯一能使用它的方法是,如果我创建一个名为其他东西的全局变量,并使用它。如果我以后需要像在"if语句"中那样引用它,这将是不实际的。
我想做的是,在test.cpp中生成varA,并在ConsoleApplication1.cpp.
您在test.cpp
顶部定义的varA
与test
类中的不同。它也从未被使用,因为在各种成员函数中,成员varA
具有优先级。
如果要将test::varA
初始化为10,请在构造函数中执行:
test::test()
: varA(10)
{
cout << "this is the test main class" << endl;
}
您可以完全摆脱test.cpp中的全局varA
。
此行:
int varA = 10;
创建一个名为varA
的新变量,该变量独立于类test
实例中的同音异义词。
基元类型,例如类test
的定义中的int varA
,默认情况下不会初始化,因此会获得-858993460
值。您可以在测试的构造函数中设置一个初始值:
test::test()
: varA(10)
{}
或者在C++11中的类声明中:
class test
{
// …
int varA = 10;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- 如何更改 int 以使其具有较小的字段来选择随机数
- 为什么当我使用一个单独类的int时,它会给我随机数