ページ 11

クラスの使い方

Posted: 2014年2月22日(土) 00:09
by 591
以下のコードで、mycar.show();は成功するのに、
showCarInfo(mycar); は失敗する理由がわかりません。
教えてください。

コード:

#include <iostream>
using namespace std;

class Car{
//private:
public:
	int number;
	int gas;
	Car(int n = 0, int g = 0){number = n; gas = g;} // Constractor
	void showCarInfo(Car& c); // Member function
	void show();
};

int main(){
	
	Car mycar(2, 4);
	showCarInfo(mycar); // Error
	mycar.show(); // Okay
	return 0;
}

// Member function
void Car::showCarInfo(Car& c){
  cout<<"The car number is "<< c.number <<endl;
  cout<<"The gas is "<< c.gas <<".\n";
}
void Car::show(){
  cout<<"The car number is "<< number <<endl;
  cout<<"The gas is "<< gas <<".\n";
}

Re: クラスの使い方

Posted: 2014年2月22日(土) 00:15
by h2so5
showCarInfoはメンバ関数ですから、呼び出すときには mycar.showCarInfo(mycar); のようにインスタンスを指定する必要があります。

Re: クラスの使い方

Posted: 2014年2月22日(土) 00:38
by 591
ありがとうございます。とても助かりました。

Re: クラスの使い方

Posted: 2014年2月22日(土) 08:56
by みけCAT
staticを用いて、このような書き方もできます。

コード:

#include <iostream>
using namespace std;

class Car{
//private:
public:
    int number;
    int gas;
    Car(int n = 0, int g = 0){number = n; gas = g;} // Constractor
    static void showCarInfo(const Car& c);
    void show() const; // Member function
};

int main(){
    
    Car mycar(2, 4);
    Car::showCarInfo(mycar); // Okay
    mycar.show(); // Okay
    return 0;
}

void Car::showCarInfo(const Car& c){
  cout<<"The car number is "<< c.number <<endl;
  cout<<"The gas is "<< c.gas <<".\n";
}
// Member function
void Car::show() const {
  cout<<"The car number is "<< number <<endl;
  cout<<"The gas is "<< gas <<".\n";
}
http://ideone.com/plAD3t

追加したconstは無くても(この場合は)動きます。