2 / 2 / 1
Регистрация: 29.01.2013
Сообщений: 47
1

valarray

22.07.2013, 13:06. Показов 1280. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Помогите разобраться, в книге есть код:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// studentc.h -- defining a Student class using containment
#ifndef STUDENTC_H_
#define STUDENTC_H_
 
#include <iostream>
#include <string>   
#include <valarray>
class Student
{   
private:
    typedef std::valarray<double> ArrayDb;
    std::string name;       // contained object
    ArrayDb scores;         // contained object
    // private method for scores output
    std::ostream & arr_out(std::ostream & os) const;
public:
    Student() : name("Null Student"), scores() {}
    explicit Student(const std::string & s)
        : name(s), scores() {}
    explicit Student(int n) : name("Nully"), scores(n) {}
    Student(const std::string & s, int n)
        : name(s), scores(n) {}
    Student(const std::string & s, const ArrayDb & a)
        : name(s), scores(a) {}
    Student(const char * str, const double * pd, int n)
        : name(str), scores(pd, n) {}
    ~Student() {}
    double Average() const;
    const std::string & Name() const;
    double & operator[](int i);
    double operator[](int i) const;
// friends
    // input
    friend std::istream & operator>>(std::istream & is,
                                     Student & stu);  // 1 word
    friend std::istream & getline(std::istream & is,
                                  Student & stu);     // 1 line
    // output
    friend std::ostream & operator<<(std::ostream & os,
                                     const Student & stu);
};
 
#endif
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// studentc.cpp -- Student class using containment
#include "studentc.h"
using std::ostream;
using std::endl;
using std::istream;
using std::string;
 
//public methods
double Student::Average() const
{
    if (scores.size() > 0)
        return scores.sum()/scores.size();  
    else
        return 0;
}
 
const string & Student::Name() const
{
    return name;
}
 
double & Student::operator[](int i)
{
    return scores[i];         // use valarray<double>::operator[]()
}
 
double Student::operator[](int i) const
{
    return scores[i];
}
 
// private method
ostream & Student::arr_out(ostream & os) const
{
    int i;
    int lim = scores.size();
    if (lim > 0)
    {
        for (i = 0; i < lim; i++)
        {
            os << scores[i] << " ";
            if (i % 5 == 4)
                os << endl;
        }
        if (i % 5 != 0)
            os << endl;
    }
    else
        os << " empty array ";
    return os; 
}
 
// friends
 
// use string version of operator>>()
istream & operator>>(istream & is, Student & stu)
{
    is >> stu.name;
    return is; 
}
 
// use string friend getline(ostream &, const string &)
istream & getline(istream & is, Student & stu)
{
    getline(is, stu.name);
    return is;
}
 
// use string version of operator<<()
ostream & operator<<(ostream & os, const Student & stu)
{
    os << "Scores for " << stu.name << ":\n";
    stu.arr_out(os);  // use private method for scores
    return os;
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// use_stuc.cpp -- using a composite class
// compile with studentc.cpp
#include <iostream>
#include "studentc.h"
using std::cin;
using std::cout;
using std::endl;
 
void set(Student & sa, int n);
 
const int pupils = 3;
const int quizzes = 5;
 
int main()
{
    Student ada[pupils] = 
        {Student(quizzes), Student(quizzes), Student(quizzes)};
 
    int i;
    for (i = 0; i < pupils; ++i)
        set(ada[i], quizzes);
    cout << "\nStudent List:\n";
    for (i = 0; i < pupils; ++i)
        cout << ada[i].Name() << endl;
    cout << "\nResults:";
    for (i = 0; i < pupils; ++i)
    {
        cout << endl << ada[i];
        cout << "average: " << ada[i].Average() << endl;
    }
    cout << "Done.\n";
    system("PAUSE");
    // cin.get();
 
    return 0;
}
 
void set(Student & sa, int n)
{
    cout << "Please enter the student's name: ";
    getline(cin, sa);
    cout << "Please enter " << n << " quiz scores:\n";
    for (int i = 0; i < n; i++)
        cin >> sa[i];
    while (cin.get() != '\n')
        continue; 
}
интересует эта часть:
C++
1
2
 Student ada[pupils] = 
        {Student(quizzes), Student(quizzes), Student(quizzes)};
в заголовочном файле не определен конструктор Student(const int n), что здесь происходит?/
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
22.07.2013, 13:06
Ответы с готовыми решениями:

valarray and complex
Вот есть такой код: double v = {0,1,2,1.3,4.2,0.5}; valarray&lt;double&gt; x(v,6); complex&lt;double&gt; ...

Библиотека valarray
Недавно спрашивал про библиотеки set и list. Там все разобрался, а вот как добавлять в valarray и...

valarray, наследование
Файл использующий объекты: 123.cpp #include &lt;iostream&gt; #include &quot;dma.h&quot; #include &lt;cstdlib&gt; ...

Класс valarray и Student
Конструктор на строке 24,25 вводит меня в замешательство. Что это за конструктор? Зачем он нужен?...

2
В астрале
Эксперт С++
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
22.07.2013, 13:09 2
А это тогда что?
C++
1
explicit Student(int n) : name("Nully"), scores(n) {}
1
2 / 2 / 1
Регистрация: 29.01.2013
Сообщений: 47
22.07.2013, 13:19  [ТС] 3
ForEveR, прошу прощения за свою невнимательность, просто я считал, что explicit только отключает преобразование, но не думал, что через него можно писать конструктор, поэтому не посмотрел дальше explicit Student(int n)
0
22.07.2013, 13:19
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
22.07.2013, 13:19
Помогаю со студенческими работами здесь

Инициализация valarray в классе
Добрый день. Требуется помощь коллективного разума: совсем забыл, как прогать. Есть следующий...

Инициализировать контейнер valarray <int>
Сгенерировать последовательность целых случайных чисел и сохранить ее в массиве.Инициализировать...

Valarray, индекс максимального элемента
Подскажите, пожалуйста в valarray есть функция myvalarray.max() А как получить индекс этого...

Непонятное поведение std::valarray
Есть такой код: #include &lt;iostream&gt; #include &lt;valarray&gt; using namespace std; int main() {...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru