简体   繁体   English

如何通过C++中的函数初始化全局变量

[英]How to initialize global variables via a function in C++

I am learning C++.我正在学习 C++。 I want to have a function to initialize my variables.我想要一个函数来初始化我的变量。 For example:例如:

#include <iostream>

double a,b
void Initializer ( double x, double y)
{
    a = x;   //a and b are global variables.
    b = y;
}
int main()
{
    Initializer(0.,4.);
    std::cout<<a<<" "<<b<<std::endl;
    return 0;
}

However, I get garbage for my global variables.但是,我的全局变量得到了垃圾。 For example I call initializer(0.,4.) , and I expect a==0 and b==4 ;例如,我调用了initializer(0.,4.) ,我期望a==0b==4 however when I print the values they are not 0,4 respectively.但是,当我打印这些值时,它们分别不是 0,4。

I do not see anything wrong about your code (except the formatting).我看不出你的代码有什么问题(格式除外)。 This is the way you can initialize global variables in both C and C++ (complete, formatted example):这是您可以在 C 和 C++ 中初始化全局变量的方式(完整的格式化示例):

#include <iostream>

void Initializer(double x, double y);

using namespace std;

double a, b;

void Initializer(double x, double y) {
    a = x;  // a and b are global variables.
    b = y;
}
int main() {
    Initializer(0.0, 4.0);
    cout << a << " " << b << endl;

    return 0;
}

Note that this line: cout << a << " " << b << endl;请注意这一行: cout << a << " " << b << endl; (together with the corresponding include and using namespace std; ) is using C++ streams. (连同相应的includeusing namespace std; )正在使用 C++ 流。 The rest could also be compiled as C code.其余的也可以编译为 C 代码。

It would also be more readable if you would provide doubles like that: Initializer(0.0, 4.0);如果您提供这样的双打,它也会更具可读性: Initializer(0.0, 4.0); . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM