为什么当我使用来自单独 class 的 int 时,它会给我随机数?

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

我对编码比较陌生,到目前为止我知道 Java 和 C++ 的基础知识,但我正在尝试更多地组织我的 cod 并稍微加快编译时间。到目前为止,我只知道如何使用其他 类 的函数。我是 self-learning 一切所以如果有人可以使用我发布的代码向我展示一个示例,那将是完美的。请随意解释,就像您在与 child 交谈一样,因为这些 Header 文件让我非常困惑。

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

ConsoleApplication1

#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 构造函数的 header 中声明的 varA 吗?我以这种方式进行了测试,它起作用了,它确实 return 10。但是,如果我想在 header/class 中使用相同的变量,在与构造函数不同的函数中,它给了我乱码再次。我似乎可以使用它的唯一方法是创建一个名为其他名称的全局变量,然后使用它。如果我以后需要像在 'if-statement'.

中那样引用它,这将是不切实际的

我想做的是,在 test.cpp 中创建 varA,并在 ConsoleApplication1.cpp.

中创建 refer/use

这一行:

int varA = 10;

创建一个名为 varAnew 变量,它独立于 class test 实例中的同音异义词。

原始类型,例如 class test 定义中的 int varA 默认情况下未初始化,因此您获得 -858993460 值。你可以在test的构造函数中设置一个初始值:

test::test()
   : varA(10)
{}

或者在 C++11 中的 class 声明中:

class test
{
    // …
    int varA = 10;
}

您在 test.cpp 之上定义的 varAtest class 中的不同。它也从未被使用过,因为在各种成员函数中,成员 varA 具有优先权。

如果要将test::varA初始化为10,在构造函数中进行:

test::test()
    : varA(10)
{
    cout << "this is the test main class" << endl;
}

您可以完全摆脱 test.cpp 中的全局 varA