Microsoft Visual C++ Windows Applications by Example phần 3

Trong lớp, chúng tôi một lần nữa sử dụng khẳng định vĩ mô trong constructor để tránh chia cho không, tất cả các số nguyên là chấp nhận được là tử số và mẫu số, ngoại trừ mẫu số không thể là zero. Số không hợp lý được đại diện bởi không như là tử số và một là mẫu số. | Chapter 2 In the class we again use the assert macro in the constructor to avoid division by zero every integer is acceptable as numerator and denominator except that the denominator cannot be zero. The zero rational number is represented by zero as numerator and one as denominator. A rational number can be assigned another number as the class overloads the assignment operator. The operator works in a way similar to the copy constructor. One difference however is that while the constructor does not return a value the assignment operator has to return its own object. One way to solve that problem is to use the this pointer which is a pointer to the object. Every non-static method of the class can access it. As the object itself shall be returned rather than a pointer to the object we first derefer the this pointer. Two rational numbers are equal if their numerators and denominators are equal. Or are they How about 1 2 and 2 4 They should be regarded as equal. So let us refine the rule to be that two rational numbers are equal if their numerators and denominators in their normalized forms are equal. A normalized rational number is a number where the numerator and the denominator have both been divided with their Greatest Common Divider which is the greatest integer that divides both the numerator and the denominator. In every equality method of the class we assume that the numbers are normalized. When testing whether two rational numbers are equal or not we do not have to re-invent the wheel. We just call the equality operator. The same goes for the less-than-or-equal-to greater-than and greater-than-or-equal-to operators. We just have to implement the less-than operator. ni n . _ - ni -d n2 d1 d1 d2 The four rules of arithmetic are implemented in their traditional mathematical way. The result of each operation is normalized. ni n d2 A ni-d2 n2. di n n2 s n1. d2 - n2. d1 di d1. d2 and d1 d2 - d . d2 n1 n2 n1 n2 _ dl d2 di d2 di d2 and d1 d2 n1. n2 71 .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
119    349    1    21-06-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.