クラスの使い方

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
591
記事: 4
登録日時: 12年前

クラスの使い方

#1

投稿記事 by 591 » 12年前

以下のコードで、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";
}

アバター
h2so5
副管理人
記事: 2212
登録日時: 15年前
住所: 東京
連絡を取る:

Re: クラスの使い方

#2

投稿記事 by h2so5 » 12年前

showCarInfoはメンバ関数ですから、呼び出すときには mycar.showCarInfo(mycar); のようにインスタンスを指定する必要があります。

591
記事: 4
登録日時: 12年前

Re: クラスの使い方

#3

投稿記事 by 591 » 12年前

ありがとうございます。とても助かりました。

アバター
みけCAT
記事: 6734
登録日時: 15年前
住所: 千葉県
連絡を取る:

Re: クラスの使い方

#4

投稿記事 by みけCAT » 12年前

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は無くても(この場合は)動きます。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

閉鎖

“C言語何でも質問掲示板” へ戻る