2016-04-30 18 views
0

私はクラスを持っており、if条件に基づいてクラスのいくつかのメンバーを宣言する必要があります。if条件付きのクラス宣言

どうすればいいですか?

Class transport(bool two_wheel=true) 
{ 

    string car, 

    string bus, 

    if (two_wheel=true) 

    { 

    string bike, 

    string cycle 

    } 

}; 
+2

謝辞実際に達成しようとしていることを説明しよう。あなたが持っているコードは確かに実行可能ではありませんが、いくつかのサブクラスを持つ 'Transport'抽象基本クラスが必要かもしれませんが...なぜ異なる文字列フィールドが必要なのかはっきりしません。 –

+0

何や理由が明確ではない。抽象度の高いデザインとして:クラストランスポートは、文字列 'string description'とホイールの' int count'という文字列を持っています。車の説明は 'car'、車輪数は' 4'です。自転車には 'bike'と' 2'などがあります。次に、他の機能を使用して必要な操作を行います。もし2つの車輪があれば、何をやるべきか分かります。 –

+0

抽象度の高いクラス「輸送」はなぜ「車」、「サイクル」などのより具体的なものに依存していますか?また、なぜそれはすべての子供たちに依存していますか?ホイールのカウントフィールドと説明フィールドを持つだけで、抽象化を再モデリングする必要があります。 – ironstone13

答えて

0

私はこれが解決策だと思う:あなたは、クラスの設計を理解する上で問題が発生しているよう

class Transport 
{ 
    bool two_wheel; 
    string car; 
    string bus; 
    string bike; 
    string cycle; 

    public Transport(bool two_wheel = true) 
    { 
     this.two_wheel = two_wheel; 
     if (two_wheel == true) 
     { 
      bike = ""; 
      cycle = ""; 
      //You'r code 
     } 
     else 
     { 
      car = ""; 
      bus = ""; 
      //You'r code 
     } 

    } 

} 
1

が見えます。

高抽象化レベルの設計として、クラスtransportには、車輪番号に対して1つの文字列string descriptionint countがあります。車の説明はcar、車輪数は4です。バイクはbike2などです。transportのインスタンスを作成すると、これをパラメータとして送信します。次に、他の機能を使用して必要な操作を行います。二輪であれば、あなたが何をすべきか知っている、そうでない、など

例:

class transport 
{ 
private: 
    std::string description; 
    int WheelsCount; 

public: 
    transport() { this->description = "Default"; this->WheelsCount = 0; } // default constructor 
    transport(std::string _description, int _WheelsCount) { this->description = _description; this->WheelsCount = _WheelsCount; } 
    // .. 
    // accessors here (getters and setters) 
    // .. 
    void MyFunction() 
    { 
     if (this->WheelsCount == 4) 
     { 
      //then it's a car, bus 
      std::cout << "Description from within your condition: " << this->description << '\n'; // do your desired task 
     } 
     else 
     { 
      // it's a bike or a cycle 
      std::cout << "Description from within your condition: "<< this->description << '\n'; // do the other task 
     } 
    } 
}; 

include <iostream><string>といくつかの楽しみを持って、main()下に使用します。

int main() 
{ 
    transport bike("Bike", 2); // create a bike 
    transport car("Car", 4); // create a car 

    bike.MyFunction(); 
    car.MyFunction(); 

    return 0; 
} 

出力を:

enter image description here

関連する問題