class getter rand变量

时间:2017-12-12 10:03:01

标签: c++ variables random

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.7/rx.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#include <iostream> #include <cstdlib> using namespace std; class Passenger { private: int ticket ; int half ; public: Passenger(int ticket=rand() % 2, int half=rand() % 2) { // Construct passenger cout << "passenger was constructed with " << ticket << " ticket and " << half << " half ticket" <<endl; } ~Passenger() { cout << "passenger was destructed" <<endl; } int getTicket()const{ cout << ticket <<endl; return ticket; }; int getHalf()const{ return half; }; }; int main(){ Passenger m; m.getTicket(); } 总是打印64而不是在调用构造函数时打印的0或1。

我无法解决这个问题,我不知道rand()

的那些东西

1 个答案:

答案 0 :(得分:2)

您正在为构造函数Passenger的参数提供默认值,但您没有初始化类属性票证的一半。

您可能已使用默认值在Passenger::Passenger中初始化了这些参数,但除非您将这些参数分配给您的函数成员,否则属性Passenger::ticketPassenger::half将不会初始化你似乎想要分配给他们的价值观。

实质上,您应该按如下方式更新构造函数:

Passenger::Passenger(int ticket=rand() % 2, int half=rand() % 2) {
    //  Construct passenger
    cout << "passenger was constructed with " << ticket << " ticket and " << half << " half ticket" <<endl;
    this->ticket = ticket;
    this->half = half;
}

您还可以使用下面给出的初始化列表。

class Passenger {
    Passenger(int ticket=rand() % 2, int half=rand() % 2) : ticket(ticket), half(half) {}
    ...  // Rest of the class definition
};