为什么当我使用一个单独类的int时,它会给我随机数

Why is it that when I use an int from a separate class, it gives me random numbers?

本文关键字:int 随机数 单独类 一个 为什么      更新时间:2023-10-16

我对编码相对较新,到目前为止我知道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顶部定义的varAtest类中的不同。它也从未被使用,因为在各种成员函数中,成员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;
}