C++ Timesaving Techniques for Dummies phần 5

mà không đòi hỏi một lớp học như đối số của nó. Ví dụ, chúng ta có thể tạo ra một khuôn mẫu với một đối số số, các bước sau chỉ cho bạn cách:Loại mã từ Liệt kê 42-1 vào tập tin của bạn. Hơn thế nữa, sao chép mã từ các nguồn tập tin trên trang Web này của cuốn sách đồng. | Technique 31 Extending a Template Class Using Non-class Template Arguments Looking at the four choices in extending base classes you will probably notice a few things that suggest particular approaches to the process. To utilize methods in a base class being used as a template you must specify which version of the class the template is to use. The reason is that you could conceivably have a class that inherited from multiple classes of the same template with different types associated with it. This is a good thing because it allows you to segregate specific functionality into separate classes. Another thing worth noticing is that you may create a templated class that does not require a class as its argument. For example we could create a template with a numeric argument the following steps show you how 1. In the code editor of your choice create a new file. In this example the file is named although you can use whatever you choose. 2. Type the code from Listing 31-3 into your file. Listing 31-3 A Template Class with a Non-class Argument template class A class LessThanTen A _element public LessThanTen A entry set entry LessThanTen const LessThanTen aCopy set void set A value - 3 if value 0 value 10 - 2 _element value A get return _element This code works for a class argument so long as that class can be compared to an integer. It can also be used for a non-class argument such as an integer long integer or even a floating point value. With this class shown in Listing 31-3 there is no reason that the template argument should be a class. In fact it would be implied that a numeric element was used since the value which is passed into the set method is compared to an integral value of 10 see the line marked - 2 . 3. Add the following code to your source file to test the integer class. This code will test the template class we just defined above. int main void LessThanTen int ten 3 - 5 printf The value is d n 23 - 4 printf The .

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
Đã 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.