简体   繁体   English

如何避免每次调用C ++函数时都重新初始化变量?

[英]How can I keep variables from being re-initialized every time I call a C++ function?

How do I get past this variable initialization problem? 我如何克服这个变量初始化问题? If I only could figure out how to only initialize them only once... 如果我只能弄清楚如何只初始化一次...

*   Main.cpp : main project file.


/**************************   Begin Header **************************/
#include "stdafx.h" //Required by Visual C ++
#include <string>   //Required to use strings
#include <iostream> //Required for a bunch of important things
#include <iomanip>  //Required for manipulation of text and numbers


using namespace System; // Automatically uses System namespace
using namespace std;    // Automatically uses std namespace


#pragma hdrstop // Stops header here
/***************************  End Header ***************************/

//* Begin Function Headers *//
void inputData(); // This will be used to organize class member calls when setting and getting new data.
int getData(); // Will get user data, input in character string, convert to an integer and then perform data validation.
void createReport(int place, int number, string type); // Will organize commands to create the report and display it on the screen.
//* End Function Headers *//



class JarsSold // Begin Class -- JarsSold
{
    /* Begin Initialization & Creation of important resources */
private:
    static const int MaxArray = 5; // Value for the size of array JARS_SOLD
    int JARS_SOLD[MaxArray]; // Creation of array with size of MaxArray
    /* End Initialization & Creation of important resources */
public: // Makes underlining elements Public instead of the default Private
    JarsSold() // Begin Constructor
    { // Put something in num array
      JARS_SOLD[0] = 0; // [1]
      JARS_SOLD[1] = 0; // [2]
      JARS_SOLD[2] = 0; // [3]
      JARS_SOLD[3] = 0; // [4]
      JARS_SOLD[4] = 0; // [5] 
    } // End Constructor
    ~JarsSold(){}; // Destructor

/* Put all members for JarsSold class below here */

    void setNumber(int num, int value) // Set the number of jars sold with number placement in array and value to replace it with
    {
        JARS_SOLD[num] = value; // Stores value into JARS_SOLD at whatever num is at the time
    }; // End setNumber class member

    int getNumber(int num) // Get the current number held for jars sold with number placement in array
    {
        return JARS_SOLD[num]; // Returns whatever is in JARS_SOLD depending on what num is at the time
    } // End getNumber class member


/* Put all members for JarsSold class above here */

}; // End Class -- JarsSold




class SalsaTypes // Begin Class -- SalsaTypes
{
    /* Begin Initialization & Creation of important resources */
private:
    static const int MaxArray = 5; // Value for the size of array JARS_SOLD
    string SALSA_TYPES[MaxArray]; // Creation of array with size of MaxArray
    /* End Initialization & Creation of important resources */

public: // Makes underlining elements public instead of the default Private
    SalsaTypes() // Begin Constructor
    { // Add default strings to str array
      SALSA_TYPES[0] = "Mild";   // [1] Stores Mild into SALSA_TYPES at 0 spot
      SALSA_TYPES[1] = "Medium"; // [2] Stores Medium into SALSA_TYPES at 1 spot
      SALSA_TYPES[2] = "Sweet";  // [3] Stores Sweet into SALSA_TYPES at 2 spot
      SALSA_TYPES[3] = "Hot";    // [4] Stores Hot into SALSA_TYPES at 3 spot
      SALSA_TYPES[4] = "Zesty";  // [5] Stores Zesty into SALSA_TYPES at 4 spot
    } // End Constructor
    ~SalsaTypes(){}; // Destructor

/* Put all members for SalsaTypes class below here */
    void setType(int num, string type) // Set salsa type with number placement in array and string value to replace with
    {
        SALSA_TYPES[num] = type; // Stores the string type into SALSA_TYPES at whatever num is at the time
    }; // End setType class member

    string getType(int num) // Get the Salsa Type with number placement in array
    {
        return SALSA_TYPES[num]; // Returns SALSA_TYPES depending on what is in num at the time
    }; // End getType class member
/* Put all members for SalsaTypes class above here */

};// End Class -- SalsaTypes


void main( void ) // Begin Main Program
{



cout << fixed << setprecision(1) << setw(2); // Do a little customization with IoManip, might as well, we just might need it

    // Main Program Contents Begin Here //

    // Opening Credits for Program
    cout << "Welcome to the /Professional Edition\\ of the Chip and Salsa Sale Tool EXPRESS." << endl;
    cout << "This handy-dandy tool will make a chip and salsa manufacturer's job much easier!" << endl;
    cout << endl << endl << endl;
    cout << "Press any key to begin inputing the number of jars sold for these salsa flavors: " << endl << endl;
    cout << "-Mild" << endl << "-Medium" << endl<< "-Sweet" << endl << "-Hot" << endl << "-Zesty" << endl << endl << endl;

    system("pause"); // Pause here. After this begin data input
    cout << endl << endl << endl;

    inputData(); // Will deal with data input, validation, and reports

    // Main Program Contents End Here //

} //End Main Program

// All Content for Functions Begin Here //
void inputData() // Begin inputData Function
{
    // Begin Create Class Obects //
    SalsaTypes salsa;
    JarsSold jars;
    // End Create Class Objects //
    // Variable Creation Begin //
    // Variable Creation End //
    // All Content for Functions Begin Here //

    for (int i = 0 ; i < 5 ; i++) // Start For Loop
    {
        cout << "Input how many Jars were sold for \"" << salsa.getType(i) << "\"" << ": "; // Displays which Salsa we are reffering to

        jars.setNumber(i,getData()); // Will use getData() to determine what value to send to the JarsSold class.
        createReport(i,jars.getNumber(i),salsa.getType(i)); // Send these numbers to another function so it can make a report later

        cout << endl << endl; // Using this as a spacer
    }

    // All Content for Functions End Here //

}; // End inputData Function

int getData() // Begin getData Function
{
    // Variable Creation Begin //
    char charData[40]; // Will be used to store user data entry
    int numTest; // Will be used for Data Validation methods
    // Variable Creation End //

    // Main Contents of Function Begin Here //
retry: // Locator for goto command

    cin >> charData; // Ask user for input. Will store in character string then convert to an integer for data validation using 'Atoi'

    numTest = atoi ( charData ); // Convert charData to integer and store in numTest

    if (numTest < 0) { numTest = 0; cout << endl << endl << "You can't enter negative numbers! Try Again." << endl << endl << "Re-enter number: "; goto retry;} // Filter out negative numbers

    // Main Contents of Function End Here //

    return numTest; // If it makes it this far, it passed all the tests. Send this value back.
}; // End getData Function

void createReport(int place, int number, string type) // Begin createReport Function
{
    // Variable Creation Begin //

    int const MAX = 5;  // Creat array size variable
    int lowest; // The integer it will use to store the place of the lowest jar sales in the array
    int highest; // The integer it will use to store the place of the highest jar sales in the array
    int total; // The integer it will use to store total sales
    int numArray[MAX];  // Create array to store jar sales (integers)
    string typeArray[MAX];  // Create array to store types of salsa (strings)

    // Variable Creation End //
    // Main Contents of Function Begin Here //

    numArray[place] = number; // Store number into new array
    typeArray[place] = type;    // Store type into new array

    if (place = 4) // If the array is full it means we are done getting data and it is time to make the report.
    { // Begin making report, If statement start

        for ( int i = 0 ; i < 5 ; i++ ) // Using a for-loop to find the highest and lowest value in the array
        { // For Loop to find high and low values BEGIN
            if ( lowest < numArray[i]) // Keep setting lowest to the lowest value until it finds the lowest one
            { // Start If
            lowest = numArray[i]; // Lowest equals whatever is in numArray at i spot
            } // End If

            if ( highest > numArray[i]) // Keep setting highest to the highest value until it finds the highest one
            { // Start If
            highest = numArray[i]; // Highest equals whatever is in numArray at i spot
            } // End If
            total += numArray[i]; // Will continually add numArray at i spot until it has the total sales
        } // For Loop to find high and low values END

    // Main Contents of Function End Here //

} // END creatReport Function
// All Content for Functions Ends Here //

Well my problem is...I need to get my data across from one function to another. 好吧,我的问题是...我需要将数据从一个功能传递到另一个功能。 I thought I could figure out how to create Global Class Objects but I couldn't. 我以为我可以弄清楚如何创建全局类对象,但我做不到。 So I thought I could get around just passing the arguments to another function and then restoring them in its own arrays and then keep doing that until i've completely copied all number arrays and string arrays. 所以我想我可以绕开这些参数,将其传递给另一个函数,然后将其还原到自己的数组中,然后继续这样做,直到我完全复制了所有数字数组和字符串数组。 Well...yeah that does work EXCEPT this part in createReport(): 好吧...是的,除了在createReport()中的这一部分之外,确实可以工作:

// Variable Creation Begin //

    int const MAX = 5;  // Create array size variable
    int lowest; // The integer it will use to store the place of the lowest jar sales in the array
    int highest; // The integer it will use to store the place of the highest jar sales in the array
    int total; // The integer it will use to store total sales
    int numArray[MAX];  // Create array to store jar sales (integers)
    string typeArray[MAX];  // Create array to store types of salsa (strings)

// Variable Creation End //

What happens is, I guess I am so tired that I missed it, every time I call that function it re-initializes those same variables again. 发生的是,我想我太累了,以至于错过了它,每次调用该函数时,它将再次重新初始化那些相同的变量。 I will put variables into another variable and then it will get re-initialized to default values. 我将变量放入另一个变量中,然后将其重新初始化为默认值。

I tried using a counter variable that counted to one after it initialized and then after it was 1 it wouldnt initialize again. 我尝试使用一个计数器变量,该变量在初始化后计数为1,然后在计数为1之后就不会再次初始化。 No that didn't work because the variables werent initialized outside the scope of the if statement. 没有,那是行不通的,因为没有在if语句的范围之外初始化变量。 I then tried a GOTO statement that would skip the initialization after it happened once. 然后,我尝试了一条GOTO语句,该语句在发生一次之后将跳过初始化。 Nope something went wrong with the first initialization phase and no compilation. 不,在第一个初始化阶段就出了问题,没有进行编译。

I need to figure out how I can either 我需要弄清楚我怎么能

  1. keep those variables from getting re-assigned or initialized so they can maintain their values. 防止这些变量被重新分配或初始化,以便它们可以保持其值。 Or 要么
  2. figure out how to create global class objects (and yes I've tried the extern classes with multiple source files. No luck just lots of errors) 弄清楚如何创建全局类对象(是的,我尝试了具有多个源文件的extern类。运气不好,只有很多错误)

I'm not very good at programming yet. 我还不太擅长编程。 But I assure you I've been working on this piece for hours and hours and hours and I stayed up all night just constantly trial and error. 但是,我向您保证,我已经在这块作品上工作了好几个小时,几个小时,而且我整夜熬夜只是不断地尝试和出错。 I really proud of myself because this code is pretty advanced for me. 我真的为自己感到骄傲,因为这段代码对我来说相当先进。 I've looked at every tutorial on Google and I'm fresh out of luck -- you guys are my last hope!! 我看过Google上的每个教程,但我很幸运,你们是我的最后希望! Sorry again guys. 再次抱歉,伙计们。 I know this is a dumb question... 我知道这是一个愚蠢的问题...

One last quick question. 最后一个快速问题。 How do you create Global Class Objects? 您如何创建全局类对象? For example 例如

MyClass
{
  MyClass(){};
  ~MyClass(){};
}

MyClass MyClassObject;

How do I use MyClassObject throughout my entire program? 如何在整个程序中使用MyClassObject?

The only way I can use it is if I create a new object every time with every function I use. 我可以使用它的唯一方法是,每次使用的每个函数都创建一个新对象。 And that means I lose all data stored inside my class? 那意味着我丢失了存储在班级中的所有数据?

I've read that having global object isn't a good idea though. 我读过,拥有全局对象并不是一个好主意。 I would love to not have to use them but I have no clue on any alternatives that I can actually understand. 我希望不必使用它们,但是我对我能真正理解的任何替代方法都不了解。

Any other critiques or tips is GREATLY appreciated. 任何其他批评或技巧都将不胜感激。 I love this stuff I just don't have many people to ask questions to. 我喜欢这些东西,只是我没有很多人要问。

You're doing really well! 你真的很好! The simple answer is to write static in front of your variables: 简单的答案是在变量前面编写static:

static int const MAX = 5;  // Creat array size variable
static int lowest; // The integer it will use to store the place of the lowest jar sales in the array
static int highest; // The integer it will use to store the place of the highest jar sales in the array
static int total; // The integer it will use to store total sales
static int numArray[MAX];  // Create array to store jar sales (integers)
static string typeArray[MAX];      // Create array to store types of salsa (strings

I think I can give you better advice though, I'll look at your code for a bit longer. 我想我可以为您提供更好的建议,我将对您的代码进行更长时间的研究。 As for global variables, what you wrote there with MyClassObject would work fine. 至于全局变量,您在那里用MyClassObject编写的内容可以正常工作。 You'd use it like this: 您可以这样使用它:

MyClass { 
public:
  MyClass(){}; 
  ~MyClass(){}; 
  int variable;
};
MyClass MyClassObject;

// in a method you'd do this
void whateverMethod() {
  MyClassObject.variable = 5;
  std::cout << MyClassObject.variable << std::endl;
}

That kind of thing. 那种事 There are some style issues that could be fixed but to be honest I say just get it working first and then we can talk about those. 有一些样式问题可以解决,但老实说,我说先让它起作用,然后我们就可以讨论这些。

1) Make them static eg 1)使其静止,例如

static string typeArray[MAX];

Initialise them once, they'll remain the same until you change them. 初始化它们一次,它们将保持不变,直到您更改它们。 Don't try and use them at the same time from two threads. 不要尝试从两个线程中同时使用它们。

2) You can create a global object by declaring it at file scope: 2)您可以通过在文件范围内声明全局对象来创建它:

class CFoo;

CFoo s_foo;

class CFoo 
{
    public:
    CFoo();
    ~CFoo();
}

Then s_foo is going to be an instance of CFoo available anywhere which can see s_foo (this file and others which have extern CFoo s_foo;) 然后s_foo将成为CFoo的一个实例,该实例可以在任何可以看到s_foo的位置使用(此文件以及其他具有外部CFoo s_foo;的文件)

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

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