You’ve seen this syntax before in Chapter 4, “Compound Types,” with the vector and array classes, and it’s pretty easy. (Those template classes also can hold numbers, but they don’t provide all the arithmetic support the valarray class does.)

The class aspect means that to use valarray objects, you need to know something about class constructors and other class methods. Here are several examples that use some of the constructors:

double gpa[5] = {3.1, 3.5, 3.8, 2.9, 3.3};

valarray v1;         // an array of double, size 0

valarray v2(8);         // an array of 8 int elements

valarray v3(10,8);      // an array of 8 int elements,

                             // each set to 10

valarray v4(gpa, 4); // an array of 4 elements

             // initialized to the first 4 elements of gpa

As you can see, you can create an empty array of zero size, an empty array of a given size, an array with all elements initialized to the same value, and an array initialized using the values from an ordinary array. With C++11, you also can use an initializer list:

valarray v5 = {20, 32, 17, 9};  // C++11

Next, here are a few of the methods:

• The operator[]() method provides access to individual elements.

• The size() method returns the number of elements.

• The sum() method returns the sum of the elements.

• The max() method returns the largest element.

• The min() method returns the smallest element.

There are many more methods, some of which are presented in Chapter 16, but you’ve already seen more than enough to proceed with this example.

The Student Class Design

At this point, the design plan for the Student class is to use a string object to represent the name and a valarray object to represent the quiz scores. How should this be done? You might be tempted to publicly derive a Student class from these two classes. That would be an example of multiple public inheritance, which C++ allows, but it would be inappropriate here. The reason is that the relationship of a student to these classes doesn’t fit the is-a model. A student is not a name. A student is not an array of quiz scores. What you have here is a has-a relationship. A student has a name, and a student has an array of quiz scores. The usual C++ technique for modeling has-a relationships is to use composition or containment—that is, to create a class composed of, or containing, members that are objects of another class. For example, you can begin a Student class declaration like this:

class Student

{

private:

    string name;              // use a string object for name

    valarray scores;  // use a valarray object for scores

    ...

};

Перейти на страницу:

Все книги серии Developer's Library

Похожие книги