簡體   English   中英

C ++-在一個函數/文件中初始化變量然后在main()/另一個文件中使用變量的最佳方法是什么?

[英]C++ - what's the best way to initialize a variable in one function/file and then use it in main()/another file?

假設在C ++中,我需要為變量分配某些內容,並且想要在main()之外進行操作,以便使代碼更清晰,但是我想將該變量用於main()或其他函數中的某些操作。 例如,我有:

int main()
{
int a = 10;
int b = 20;
SomeFunction(a,b);
}

我想要這樣的東西:

void Init()
{
int a = 10;
int b = 20;
}

int main()
{
SomeFunction(a,b);
}

但是顯然編譯器會說a和b在main()范圍內未聲明。 我總是可以將它們聲明為全局變量,但是可能有解決該問題的更好方法,而且我讀到,從長遠來看,全局變量並不是那么好。 我不想使用類。 你們有什么建議?

使用結構:

struct data
{
    int x;
    int y;
};

data Init()
{
    data ret;
    ret.x = 2;
    ret.y = 5;
    return ret;
}

int main()
{
    data v = Init();
    SomeFunction(v.x, v.y); //or change the function and pass there the structure
    return 0;
}

如果您不想使用偶數結構,則可以通過引用將值傳遞給Init函數。 但我認為第一個版本更好。

void Init(int &a, int &b)
{
    a = 5;
    b = 6;
}

int main()
{
    int a, b;
    Init(a, b);
    return 0;
}

您可以使用extern關鍵字。 它允許變量定義一次,然后在任何地方使用。 您可以像這樣使用它:

// main.cpp

extern int a;
extern int b;

並在您的其他文件中

// Other.cpp

int a = 10;
int b = 20;

您可以根據需要多次使用extern聲明它們,但是只能定義一次。

您可以在此處閱讀有關extern更多信息。

根據具體情況,您可能需要將這些變量的值存儲在文件中,並在需要時從磁盤讀取它們。 例如,您可能具有data_values.txt,其中您使用空格分隔的整數:324 26 435...。

然后在另一個源文件中定義一個文件讀取功能,例如data_reader.cpp:

#include<fstream>
#include<string>
#include<vector>

std::vector<int> get_data(const std::string& file_name){
  // Initialize a file stream
  std::ifstream data_stream(file_name);

  // Initialize return
  std::vector<int> values;

  // Read space separated integers into temp and add them to the back of
  // the vector.
  for (int temp; data_stream >> temp; values.push_back(temp)) 
  {} // No loop body is necessary.

  return values;
}

在要使用該功能的任何文件中,

#include <string>
#include <vector>
// Function declaration
std::vector<int> get_data(const std::string& file_name);
// File where the data is stored
const std::string my_data_file {"data_values.txt"};

void my_function() {
... // do stuff here
std::vector<int> data_values = get_data(my_data_file);
... // process data
}

如果還避免使用C ++標准庫中的類,則可能要使用int數組作為返回值,將char *或char數組用作文件名,並使用scanf或其他一些C函數讀取文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM