C ++ 함수를 호출 할 때마다 변수가 다시 시작되지 않도록하려면 어떻게해야합니까?

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

  •  20-08-2019
  •  | 
  •  

문제

이 변수 초기화 문제를 어떻게 지나가나요? 한 번만 초기화하는 방법 만 알아낼 수 있다면 ...

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

글쎄 내 문제는 ... 한 기능에서 다른 기능으로 내 데이터를 가져와야합니다. 글로벌 클래스 객체를 만드는 방법을 알아낼 수 있다고 생각했지만 할 수 없었습니다. 그래서 나는 인수를 다른 함수로 전달한 다음 자체 배열로 복원 한 다음 모든 숫자 배열과 문자열 배열을 완전히 복사 할 때까지 계속 수행 할 수 있다고 생각했습니다. 글쎄 ... 그래 크레이터 피트 () 에서이 부분을 제외하고는 작동합니다.

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

무슨 일이 일어나는지, 나는 너무 피곤해서 그것을 놓치고 있었기 때문에 그 기능을 호출 할 때마다 동일한 변수를 다시 시작합니다. 변수를 다른 변수에 넣은 다음 기본값으로 다시 시작됩니다.

초기화 된 후 하나에 계산 된 카운터 변수를 사용하려고 시도한 다음 1이면 다시 초기화되지 않았습니다. 변수가 IF 문의 범위 밖에서 초기화 되었기 때문에 작동하지 않았습니다. 그런 다음 한 번 발생한 후 초기화를 건너 뛰는 GOTO 문을 시도했습니다. 첫 번째 초기화 단계와 컴파일이 없으면 문제가 발생했습니다.

내가 어떻게 할 수 있는지 알아 내야합니다

  1. 해당 변수가 다시 할당되거나 초기화되지 않도록 유지하여 값을 유지할 수 있습니다. 또는
  2. 글로벌 클래스 객체를 만드는 방법을 알아냅니다 (예, 여러 소스 파일로 외부 클래스를 시도했습니다. 운이 좋지 않습니다.

나는 아직 프로그래밍에 능숙하지 않습니다. 그러나 나는 당신에게 몇 시간과 몇 시간 동안이 작품을 작업하고 있다고 확신하고, 나는 밤새 끊임없이 시행 착오를 유지했습니다. 나는이 코드가 나에게 상당히 발전했기 때문에 나 자신을 정말로 자랑스럽게 생각한다. 나는 Google의 모든 튜토리얼을 보았고 운이 좋지 않은 신선한 것입니다. 여러분은 나의 마지막 희망입니다 !! 다시 죄송합니다. 나는 이것이 바보 같은 질문이라는 것을 알고있다 ...

마지막으로 빠른 질문 중 하나입니다. 글로벌 클래스 객체를 어떻게 만들 수 있습니까? 예를 들어

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

MyClass MyClassObject;

전체 프로그램에서 myclassobject를 어떻게 사용합니까?

내가 사용할 수있는 유일한 방법은 내가 사용하는 모든 함수로 매번 새 객체를 만드는 것입니다. 그리고 그것은 수업에 저장된 모든 데이터를 잃어버린 것을 의미합니까?

나는 글로벌 객체를 갖는 것이 좋은 생각이 아니라는 것을 읽었습니다. 나는 그것들을 사용할 필요가 없지만 실제로 이해할 수있는 대안에 대한 단서가 없습니다.

다른 비판이나 팁은 대단히 감사합니다. 나는이 물건을 좋아합니다. 나는 단지 질문을 할 사람이 많지 않습니다.

도움이 되었습니까?

해결책

당신은 정말 잘하고 있습니다! 간단한 대답은 변수 앞에 정적을 작성하는 것입니다.

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

나는 당신에게 더 나은 조언을 줄 수 있다고 생각합니다. 나는 당신의 코드를 조금 더 오랫동안 살펴볼 것입니다. 글로벌 변수의 경우 MyClassObject와 함께 작성한 내용은 잘 작동합니다. 당신은 이것을 사용합니다 :

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

그런 종류의 것. 고칠 수있는 몇 가지 스타일 문제가 있지만 솔직히 말해서 먼저 작동하게 한 다음 우리는 그것에 대해 이야기 할 수 있습니다.

다른 팁

1) 정적을 정적으로 만드십시오

static string typeArray[MAX];

한 번 초기화하면 변경할 때까지 동일하게 유지됩니다. 두 스레드에서 동시에 사용하려고 시도하지 마십시오.

2) 파일 범위로 선언하여 글로벌 객체를 만들 수 있습니다.

class CFoo;

CFoo s_foo;

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

그런 다음 s_foo는 s_foo (이 파일과 외부 cfoo s_foo가있는 다른 파일;)를 볼 수있는 CFOO의 인스턴스가 될 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top