简体   繁体   English

成员函数的指针

[英]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.我目前正在尝试创建一个程序,通过将数组传递给 class 的成员 function 来计算具有给定时间值的火箭的质量。 I want to use a pointer for the array.我想为数组使用指针。 How do I go about doing that.我该怎么做 go。 Should the pointer be initialized in int main or the class.指针应该在 int main 还是 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. equip是一个非常大的object。 About 14 gigabytes in fact.实际上大约 14 GB。

Automatic variables such as equip rocket are allocated on the execution stack.诸如equip rocket之类的自动变量被分配在执行堆栈上。 The default size of the execution stack on most desktop systems is about 1 to few megabytes.大多数桌面系统上执行堆栈的默认大小约为 1 到几兆字节。

A 14 gigabyte object will most definitely overflow a 1 megabyte stack. 14 GB 的 object 肯定会溢出 1 MB 的堆栈。

Solution: Always use dynamic allocation for large arrays such as used here.解决方案:总是对大的 arrays 使用动态分配,例如这里使用的。 Simplest solution is to use std::vector .最简单的解决方案是使用std::vector Also, are you certain that you need the arrays to be that big?另外,您确定需要那么大的 arrays 吗?


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

This loop looks like it will never end because 999999999 is always true.这个循环看起来永远不会结束,因为 999999999 总是正确的。

 { return....

But in fact, the loop never repeats because the function immediately returns.但实际上,循环永远不会重复,因为 function 会立即返回。 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.如果不能,go 通过动态 memory 分配。

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

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