查看完整版本: 問物件導向程式,該如何修改~
頁: [1]

sam戚 發表於 2017-2-24 10:04 PM

問物件導向程式,該如何修改~

本帖最後由 sam戚 於 2017-2-24 10:04 PM 編輯

請問高手以下是題目和程式碼,要如何修改程式碼以符合題目之意,並成功執行,求解~Tks


題目:
請以物件設計 BMI,data fields(都是 private): string name, double weight, doubl e height,functions: 建構者, double getWeight() ,double getHeight(), double getBMI()。BMI = weight  / (height*height)。主程式建立"王小明 80 1.7", 最後輸出 姓名和 BMI。不論 BMI 是否為整數,請輸出到小數點後兩位。
範例輸出:王小明 27.68


程式碼:
#include <iostream>
#include <iomanip>
#include <string.h>

using namespace std;

class BMI
{
private:
  string name;
  double weight;
  double height;

public:        
        BMI()
        {
                weight = 1;
                height = 1;
        }

        BMI(string newName,double newWeight,double newHeight)
        {
                name = newName;
                weight = newWeight;
                height = newHeight;
        }

  double getBMI()
  {
          return weight / (height*height);
  }

  double getWeight()
  {
          return weight;
  }

  double getHeight()
  {
          return height;
  }
};

int main()
{
  BMI bmi("王小明",80,1.7);
  cout<<bmi.name<<"\t"<<setprecision(2)<<fixed<<bmi.getBMI();

}

...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div><div></div>

last60407 發表於 2017-2-25 03:36 PM

在class最後加上
string getname()
{
                  return name;
}
然後把第一個輸出"bmi.name"改成"bmi.getname()"就可以了,希望有解決你的問題{:37:}

chyu1019 發表於 2017-3-23 03:47 PM

name 在private下, 要嘛有member function存取private variable, 要嘛就直接宣告成public member, 這樣就沒存取限制

o_g349 發表於 2017-9-13 01:01 PM

last60407 發表於 2017-2-25 03:36 PM static/image/common/back.gif
在class最後加上
string getname()
{


大致上是對的,但是要完全符合題目要求 getname() 應該要改成 getName(),保持函數命名的一致性
頁: [1]