用if条件声明类

时间:2016-04-30 07:38:25

标签: c# class

我有一个课程,我需要根据if条件声明该课程的几个成员。

我该怎么做?

Class transport(bool two_wheel=true)
{

   string car,

   string bus,

   if ( two_wheel=true)

   {

     string bike,

     string cycle

   }

};

1 个答案:

答案 0 :(得分:1)

看起来您在理解课程设计时遇到了问题。这应该可以帮助你找到一个好的:

作为高抽象级别设计:类transport有一个字符串string description和一个int 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