簡體   English   中英

[C ++]變量跨.cpp文件

[英][C++]Variables cross .cpp files

這是一個愚蠢的問題,有些問題一定是一個簡單的答案,但是經過數小時的搜索,我找不到答案。 我需要做的是有一對.cpp文件,例如main.cpp和help.cpp,它們有一個變量vars1,它們共享並且可以更改值並檢測何時更改了該值。 對我來說有意義的方法是,我只需要在頭文件中的類中聲明變量,然后在兩個.cpp文件中都包含該頭文件,但這似乎不起作用。

這是我的代碼的副本:

#include <iostream>
#include <fstream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "variables1.h"

using namespace std;

int main(){
variables1 vars1;

do {
    cout << "Welcome\n If you need help, type 'yes' now\n";
    cin.getline(vars1.input, 1024);
    if (strcmp(vars1.input, "yes") == 0 || strcmp(vars1.input, "Yes") == 0){
        vars1.helpvar = true;
        cin.get();
    }
    else{
        cout << "Okay then, glad that you know your way around\n";
    }
    cin.clear();
    cout << "What would you like to do?\n";
    cin.getline(vars1.input, 1024);
    if (strcmp(vars1.input, "logon" ) == 0 ) {

    }
} while (0 == 0);
}

help.cpp:

#include <iostream>
#include "variables1.h"

using namespace std;

int help(){
    variables1 vars1;
    do {
        if (vars1.helpvar == true)
            cout << "detecting";
    } while (0 == 0);
}

variables1.h:

class variables1
{
public:
    bool helpvar;
    char input[1024];
};

實際上,您正在為主文件和help.cpp創建兩個不同的對象,並分別為每個對象設置helpvar變量。 您想要的是只有一個對象,help.cpp和main都使用該對象來僅修改helpvar變量的單個實例。

更改您的幫助功能,使其與

int help(const variables1& myHelpobject ){
    if (myHelpobject.helpvar == true) {
            cout << "detecting";
    }
}

然后在main中將函數調用為:

help(vars1)

您之前所做的是創建一個單獨的,獨立的幫助對象。

在這里,我們在main中創建對象,然后將對它的引用傳遞給函數。

使用的技術取決於變量的目的。

如果必須在所有代碼中使用某種全局參數 ,則最簡單的方法是將其定義為全局變量:

主文件:

variables1 vars1;  // outside all functions
int main(){
...
}

在variable1.h或其他使用該變量的cpp文件中:

extern variables1 vars1;  //outside all functions 

但是,也應該在類中定義用於初始化和維護這些變量的代碼。 例如,構造函數應默認定義值,例如啟用或禁用幫助。

如果您的變量用於在代碼的不同部分之間進行通信 ,特別是如果某些代碼的主要目標是處理這些變量的內容,則最好通過將變量作為參數傳遞(如果引用,則使用通信是雙向的或按值進行的)。

發布的代碼有兩個主要問題:

int help()永遠不會運行

需要調用此函數才能使其運行。 沒有任何操作,因此無論vars1.helpvar的值如何,您都永遠不會看到"detecting"輸出。

考慮添加帶有該函數定義的help.hpp並從main調用該函數。

vars1.helpvar在main和int help()之間不共享

當前,您有兩個variables1實例,而helpvar是成員變量,因此每個實例都有一個單獨的副本。

您可以:

  1. 使helpvar成為variables1的靜態成員
  2. mainhelp之間共享一次variables1實例。

使用靜態變量更有可能在以后給設計帶來問題,因此我贊成選項2。

暫無
暫無

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

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