Comment empêcher les variables d'être réinitialisées chaque fois que j'appelle une fonction C ++?

StackOverflow https://stackoverflow.com/questions/495540

  •  20-08-2019
  •  | 
  •  

Question

Comment surmonter ce problème d'initialisation de variable? Si seulement je pouvais comprendre comment les initialiser une seule fois ...

*   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 //

Eh bien, mon problème est ... Je dois transférer mes données d'une fonction à une autre. Je pensais pouvoir comprendre comment créer des objets de classe globale, mais je ne le pouvais pas. J'ai donc pensé que je pourrais contourner le problème en passant les arguments à une autre fonction, puis en les restaurant dans ses propres tableaux, puis le faire jusqu'à ce que j'ai complètement copié tous les tableaux de nombres et de tableaux. Eh bien ... oui ça marche SAUF cette partie dans 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 //

Ce qui se passe, c’est que je suis tellement fatigué que je l’ai manquée, chaque fois que j’appelle cette fonction, elle réinitialise à nouveau ces mêmes variables. Je vais mettre les variables dans une autre variable, puis il sera réinitialisé aux valeurs par défaut.

J'ai essayé d'utiliser une variable de compteur qui comptait jusqu'à une après son initialisation, puis après 1, elle ne s'initialisait plus. Non, cela n'a pas fonctionné car les variables n'étaient pas initialisées en dehors de la portée de l'instruction if. J'ai ensuite essayé une instruction GOTO qui ignorerait l'initialisation une fois que cela s'est produit. Quelque chose ne va pas avec la première phase d'initialisation et pas de compilation.

Je dois savoir comment je peux soit

  1. empêche ces variables d’être réattribuées ou initialisées afin de pouvoir conserver leurs valeurs. Ou
  2. comprendre comment créer des objets de classe globaux (et oui, j'ai essayé les classes externes avec plusieurs fichiers source. Pas de chance, il y a beaucoup d'erreurs)

Je ne suis pas encore très bon en programmation. Mais je vous assure que je travaille sur cette pièce depuis des heures et des heures et que je suis restée debout toute la nuit sans cesse à essayer et à faire des erreurs. Je suis vraiment fier de moi car ce code est assez avancé pour moi. J'ai consulté tous les tutoriels sur Google et je n'ai plus de chance - vous êtes mon dernier espoir !! Désolé encore les gars. Je sais que c'est une question idiote ...

Une dernière question rapide. Comment créez-vous des objets de classe globale? Par exemple

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

MyClass MyClassObject;

Comment utiliser MyClassObject tout au long de mon programme?

La seule façon de l'utiliser est de créer un nouvel objet à chaque fois avec chaque fonction que j'utilise. Et cela signifie que je perds toutes les données stockées dans ma classe?

J'ai lu qu'avoir un objet global n'était pas une bonne idée cependant. J'adorerais ne pas avoir à les utiliser, mais je n'ai aucune idée de toute solution de rechange que je puisse réellement comprendre.

Toute autre critique ou astuce est grandement appréciée. J'aime ce genre de choses et je n'ai pas beaucoup de gens à qui poser des questions.

Était-ce utile?

La solution

Tu vas vraiment bien! La réponse simple est d'écrire statique devant vos variables:

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

Je pense pouvoir vous donner de meilleurs conseils, je vais regarder votre code un peu plus longtemps. En ce qui concerne les variables globales, ce que vous avez écrit ici avec MyClassObject fonctionnerait correctement. Vous l'utiliseriez comme ceci:

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

Ce genre de chose. Il y a des problèmes de style qui pourraient être résolus, mais pour être honnête, je dis juste de commencer par le faire fonctionner, puis nous pourrons en parler.

Autres conseils

1) Rendez-les statiques, par exemple

static string typeArray[MAX];

Initialisez-les une fois, ils resteront les mêmes jusqu'à ce que vous les changiez. N'essayez pas de les utiliser en même temps à partir de deux threads.

2) Vous pouvez créer un objet global en le déclarant à la portée du fichier:

class CFoo;

CFoo s_foo;

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

Ensuite, s_foo va devenir une instance de CFoo disponible partout où il est possible de voir s_foo (ce fichier et d’autres qui ont un extern CFoo s_foo;)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top