简体   繁体   中英

Pointers for Member Functions

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I want to use a pointer for the array. How do I go about doing that. Should the pointer be initialized in int main or the class. Any suggestions appreciated.

#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>

using namespace std;

class equip
{
public:
    double mass[999999999], velocity, height, *time[999999999];
    double calcmass(double* time); 
    double calcvelocity();
    double calcheight();
    double calctime();
private:
    double T = 7000;
    double g = 32.2;
    double K = 0.008;
};

double equip::calcmass(double* time)
{
    int i = 0;
    for(i=0; i=999999999; i++)
    {
        return mass[i] = (3000 - 40 * time[i]) / g;
    }
}

int main()
{
    int i = 0;
    equip rocket;
    ifstream infile;
    string filename;
    cout<<"Enter input file name for time values: ";
    cin>>filename;
    infile.open(filename.c_str());

    while(infile.fail())
    {
        cerr<<"Error opening file. \n";
        cout<<"Enter file name: ";
        cin>>filename;
        infile.open(filename.c_str());
    }

    for(i=0; i<999999999; i++)
    {
        infile>>rocket.time[i];
    }

    for(i=0; i<999999999; i++)
    {
        cout<<rocket.mass[i];
    }

    return 0;
}

equip is a very large object. About 14 gigabytes in fact.

Automatic variables such as equip rocket are allocated on the execution stack. The default size of the execution stack on most desktop systems is about 1 to few megabytes.

A 14 gigabyte object will most definitely overflow a 1 megabyte stack.

Solution: Always use dynamic allocation for large arrays such as used here. Simplest solution is to use std::vector . Also, are you certain that you need the arrays to be that big?


 for(i=0; i=999999999; i++)

This loop looks like it will never end because 999999999 is always true.

 { return....

But in fact, the loop never repeats because the function immediately returns. Neither choice makes sense, although in combination their silliness sort of cancel each other out.

Change the size of array to a practical real number. If can't, go through Dynamic memory allocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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