c ++类传递成员函数问题

时间:2015-04-12 02:33:52

标签: c++ function class

在课堂上学习类和结构,我正在研究一个应该在类中有成员函数的程序,一个做计算而另一个用来返回某些值,看起来我遇到麻烦调用函数可能? IM不是100%肯定,因为c ++不能指定错误。我希望你能帮助我,提前谢谢你。

#include <iostream>
#include <cstdlib>
using namespace std; 
void rocket(double massR,double massE, double massP,double avgTh,double bd);
double rocketreturn(double& MV,double& MA);

class Rocket
{
private:
 double massR;
 double massE;
 double massP;
 double avgTh; // average thrust
 double bd;    //burn duration

public:

void rocket(double massR,double massE, double massP,double avgTh,double bd) 
{
 massR=massR/1000;
 massE=massE/1000;
 massP=massP/1000;
 double LM=massR+massE;
 double MCP=massR+massE-massP;
 double AM=(LM+MCP)/2;
 double acc=(avgTh/AM)-9.8;
 double MV= acc * bd;
 double Alt=.5*acc*.5*.5;
 double t=MV/9.8; 
 double MA=Alt+MV*t+.5*-9.8*t*t;
  }

 double rocketreturn(double& MV, double& MA)
 {
 cout<< MV;
 cout<< MA;
 }
};



int main( )
{
double massR; // mass of the rocket
double massE; // mass of the engine
double massP; // mass of the propellant
double avgTh; // average thrust
double bd; // burn duration
double MV; // max velocity
double MA; // max altitude
char ans;
system("CLS");
cout << "Take Home # by - "
     << "Rocket Object\n\n";

do
{
cout <<"Enter the mass of the rocket: "<<endl;
cin >> massR;   
cout <<"Enter the mass of the engine: "<<endl;
cin >> massE;
cout <<"Enter the mass of the propellant: "<<endl;
cin >> massP;
cout <<"Enter the average thrust of the engine: "<<endl;
cin >> avgTh;
cout <<"Enter the burn duration of the engine: "<<endl;
cin >> bd;

rocketreturn(MV,MA);

cout <<"the rockets maximum velocity is " << MV<<endl;
cout <<"the rockets maximum altitude is "<<MA<<endl;

cout <<"Would you like to run the program again (Y or N)?"<<endl;
cin>>ans;
}
while(ans=='y'||ans=='Y');

}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下程序结构并按照您希望的方式填写详细信息。 注意,它不会编译。

#include <iostream>

using namespace std;

class Rocket {
  private:
    double mR, mE;
  public:
    /* Constructor. It is missing in your program. You probably want it */
    Rocket(double massR, double massE) {
      /* Better to use initialization list, but this should work too */
      mR = massR;
      mE = massE;
    }

    double rocketreturn(double & a, double & b) {
      /* Do sth with the parameters. But return a double, 
         which you are not doing in your program */
       double result = a + b;
       return result;
    }

};

int main() {
    double x, y;
    do {
        cin >> x >> y;
        Rocket my_rocket(x, y);
        double z = my_rocket.rocketreturn(x, y);  // Assignment not necessary

    } while ( /* some condition */) //my_rocket object will be destroyed after scope goes out
    return 0;
}