簡體   English   中英

成員函數的指針

[英]Pointers for Member Functions

我目前正在嘗試創建一個程序,通過將數組傳遞給 class 的成員 function 來計算具有給定時間值的火箭的質量。 我想為數組使用指針。 我該怎么做 go。 指針應該在 int main 還是 class 中初始化。 任何建議表示贊賞。

#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是一個非常大的object。 實際上大約 14 GB。

諸如equip rocket之類的自動變量被分配在執行堆棧上。 大多數桌面系統上執行堆棧的默認大小約為 1 到幾兆字節。

14 GB 的 object 肯定會溢出 1 MB 的堆棧。

解決方案:總是對大的 arrays 使用動態分配,例如這里使用的。 最簡單的解決方案是使用std::vector 另外,您確定需要那么大的 arrays 嗎?


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

這個循環看起來永遠不會結束,因為 999999999 總是正確的。

 { return....

但實際上,循環永遠不會重復,因為 function 會立即返回。 這兩種選擇都沒有意義,盡管它們的愚蠢結合在一起可以相互抵消。

將數組的大小更改為實際的實數。 如果不能,go 通過動態 memory 分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM