Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.69/13: Рейтинг темы: голосов - 13, средняя оценка - 4.69
0 / 0 / 0
Регистрация: 24.05.2015
Сообщений: 9
1

Как правильно сделать #include "Sales_item.h" ?

11.08.2015, 09:43. Показов 2553. Ответов 21
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
C++ Скопировано
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#ifndef Sales_Item_HPP
#define Sales_Item_HPP
#include "Sales_item.h"
#endif Sales_Item_HPP
using namespace std;
 
int main()
{
    Sales_item book;
    cin >> book;
    cout << book << endl;
 
    system("pause");
    return 0;
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
11.08.2015, 09:43
Ответы с готовыми решениями:

#include "Sales_item.h" - ошибка "включаемый файл включает самого себя"
Пишу в файле Sales_item.h следующее: #include &quot;Sales_item.h&quot; #include &lt;iostream&gt; void main() { Sales_item book; //тут...

Работа с файлами в C# с исп. библиотек #include <stdio.h> #include <stdlib.h> #include <math.h> #include <io.h>
В типизированном файле записаны названия городов и их численность. Увеличить численность каждого города на 5% (Количество жителей всегда...

Как правильно сделать include
Всем привет. Научите правильно делать include. имеется основной скрипт с формой, которой связан с главной страницей. Но мне эта форма нужна...

21
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5287 / 2374 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
11.08.2015, 12:49 21
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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*
 * This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
 * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
 * copyright and warranty notices given in that book:
 * 
 * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
 * 
 * 
 * "The authors and publisher have taken care in the preparation of this book,
 * but make no expressed or implied warranty of any kind and assume no
 * responsibility for errors or omissions. No liability is assumed for
 * incidental or consequential damages in connection with or arising out of the
 * use of the information or programs contained herein."
 * 
 * Permission is granted for this code to be used for educational purposes in
 * association with the book, given proper citation if and when posted or
 * reproduced.Any commercial use of this code requires the explicit written
 * permission of the publisher, Addison-Wesley Professional, a division of
 * Pearson Education, Inc. Send your request for permission, stating clearly
 * what code you would like to use, and in what specific way, to the following
 * address: 
 * 
 *     Pearson Education, Inc.
 *     Rights and Permissions Department
 *     One Lake Street
 *     Upper Saddle River, NJ  07458
 *     Fax: (201) 236-3290
*/ 
 
/* This file defines the Sales_item class used in chapter 1.
 * The code used in this file will be explained in 
 * Chapter 7 (Classes) and Chapter 14 (Overloaded Operators)
 * Readers shouldn't try to understand the code in this file
 * until they have read those chapters.
*/
 
#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined 
#define SALESITEM_H
 
#include "Version_test.h" 
 
// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>
 
class Sales_item {
// these declarations are explained section 7.2.1, p. 270 
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool 
operator==(const Sales_item&, const Sales_item&);
public:
    // constructors are explained in section 7.1.4, pages 262 - 265
    // default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
    Sales_item() = default;
#else
    Sales_item(): units_sold(0), revenue(0.0) { }
#endif
    Sales_item(const std::string &book):
              bookNo(book), units_sold(0), revenue(0.0) { }
    Sales_item(std::istream &is) { is >> *this; }
public:
    // operations on Sales_item objects
    // member binary operator: left-hand operand bound to implicit this pointer
    Sales_item& operator+=(const Sales_item&);
    
    // operations on Sales_item objects
    std::string isbn() const { return bookNo; }
    double avg_price() const;
// private members as before
private:
    std::string bookNo;      // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
    unsigned units_sold = 0; // explicitly initialized
    double revenue = 0.0;
#else
    unsigned units_sold;  
    double revenue;       
#endif
};
 
// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs) 
{ return lhs.isbn() == rhs.isbn(); }
 
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);
 
inline bool 
operator==(const Sales_item &lhs, const Sales_item &rhs)
{
    // must be made a friend of Sales_item
    return lhs.units_sold == rhs.units_sold &&
           lhs.revenue == rhs.revenue &&
           lhs.isbn() == rhs.isbn();
}
 
inline bool 
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
    return !(lhs == rhs); // != defined in terms of operator==
}
 
// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs) 
{
    units_sold += rhs.units_sold; 
    revenue += rhs.revenue; 
    return *this;
}
 
// assumes that both objects refer to the same ISBN
Sales_item 
operator+(const Sales_item& lhs, const Sales_item& rhs) 
{
    Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
    ret += rhs;           // add in the contents of (|rhs|) 
    return ret;           // return (|ret|) by value
}
 
std::istream& 
operator>>(std::istream& in, Sales_item& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
        s.revenue = s.units_sold * price;
    else 
        s = Sales_item();  // input failed: reset object to default state
    return in;
}
 
std::ostream& 
operator<<(std::ostream& out, const Sales_item& s)
{
    out << s.isbn() << " " << s.units_sold << " "
        << s.revenue << " " << s.avg_price();
    return out;
}
 
double Sales_item::avg_price() const
{
    if (units_sold) 
        return revenue/units_sold; 
    else 
        return 0;
}
#endif
Добавлено через 3 минуты
И вот ещё Version_test.h
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
76
77
78
79
80
/*
 * This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
 * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
 * copyright and warranty notices given in that book:
 * 
 * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
 * 
 * 
 * "The authors and publisher have taken care in the preparation of this book,
 * but make no expressed or implied warranty of any kind and assume no
 * responsibility for errors or omissions. No liability is assumed for
 * incidental or consequential damages in connection with or arising out of the
 * use of the information or programs contained herein."
 * 
 * Permission is granted for this code to be used for educational purposes in
 * association with the book, given proper citation if and when posted or
 * reproduced. Any commercial use of this code requires the explicit written
 * permission of the publisher, Addison-Wesley Professional, a division of
 * Pearson Education, Inc. Send your request for permission, stating clearly
 * what code you would like to use, and in what specific way, to the following
 * address: 
 * 
 *  Pearson Education, Inc.
 *  Rights and Permissions Department
 *  One Lake Street
 *  Upper Saddle River, NJ  07458
 *  Fax: (201) 236-3290
*/
 
#ifndef VERSION_TEST_H
#define VERSION_TEST_H
 
/* As of the first printing of C++ Primer, 5th Edition (July 2012), 
 * the Microsoft Complier did not yet support a number of C++ 11 features.  
 *
 * The code we distribute contains both normal C++ code and 
 * workarounds for missing features.  We use a series of CPP variables to
 * determine whether a given features is implemented in a given release
 * of the MS compiler.  The base version we used to test the code in the book
 * is Compiler Version 17.00.50522.1 for x86.
 *
 * When new releases are available we will update this file which will
 * #define the features implmented in that release.
*/
 
#if _MSC_FULL_VER == 170050522 || _MSC_FULL_VER == 170050727 
// base version, future releases will #define those features as they are
// implemented by Microsoft
 
/* Code in this delivery use the following variables to control compilation
 
   Variable tests           C++ 11 Feature 
CONSTEXPR_VARS            constexpr variables
CONSTEXPR_FCNS            constexpr functions
CONSTEXPR_CTORS           constexpr constructors and other member functions
DEFAULT_FCNS              = default 
DELETED_FCNS              = delete  
FUNC_CPP                  __func__ local static
FUNCTION_PTRMEM           function template with pointer to member function
IN_CLASS_INITS            in class initializers 
INITIALIZER_LIST          library initializer_list<T> template
LIST_INIT                 list initialization of ordinary variables
LROUND                    lround function in cmath
NOEXCEPT                  noexcept specifier and noexcept operator
SIZEOF_MEMBER             sizeof class_name::member_name
TEMPLATE_FCN_DEFAULT_ARGS default template arguments for function templates
TYPE_ALIAS_DECLS          type alias declarations
UNION_CLASS_MEMS          unions members that have constructors or copy control
VARIADICS                 variadic templates
*/
#endif  // ends compiler version check
 
#ifndef LROUND
inline long lround(double d)
{
    return (d >= 0) ?  long(d + 0.5) : long(d - 0.5);
}
#endif
 
#endif  // ends header guard
1
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5287 / 2374 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
11.08.2015, 12:52 22
Ня, вот Вам весь архив с файлами из книги:
Вложения
Тип файла: zip LippmanFiles(VisualStudio2012).zip (483.3 Кб, 6 просмотров)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
11.08.2015, 12:52
Помогаю со студенческими работами здесь

Как правильно подключать include?
Доброго вечера суток господа. Подскажите что я делаю не так? Есть два файла config.php и login.php &lt;?php $MySQL_HOST =...

Как правильно защитить include от прямого вызова?
Всем привет! Хочу защитить include от прямого вызова, при этом чтобы выводилась моя страница ошибки (error/403.php). Не знаю как это...

Как правильно подключать файлы через include?
Есть основная папка с проектом. В ней находится ещё несколько папок. В index.php который находится в папке Project_Folder делаю...

include require как подключить правильно файл
Проблема в следующем: Нужно подключить файл который находиться в другой директории. Имеем файл &quot;сайт/папка/папка/индекс.пхп&quot; ...

Как правильно подключить Include файлы в PHP? При подключении получаются ошибки
Создаю сайт, в дереве сайта создал папки( пишу то, что относится к проблеме ): include, pages. В корне сайта создал Index файл, в нем вывел...


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

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

Редактор формул (кликните на картинку в правом углу, чтобы закрыть)
Новые блоги и статьи
Безопасность кластеров Apache Kafka
Javaican 14.03.2025
Apache Kafka стал одним из ключевых компонентов современных архитектур, обрабатывающих потоки данных в режиме реального времени. Его используют тысячи компаний от стартапов до технологических. . .
Контейнеризация ML моделей с помощью Docker и Kubernetes
Mr. Docker 14.03.2025
Перенос ML-моделей из лаборатории в продакшн сопровождается целым комплексом проблем. Нередко код, который отлично работает на локальной машине, отказывается функционировать в промышленной среде. . . .
Организация масштабируемого хранилища с Apache Cassandra
Codd 14.03.2025
Изначально разработанная в Facebook, а затем переданная Apache Software Foundation, Cassandra сочетает в себе принципы Amazon's Dynamo и Google's BigTable. Эта комбинация создает уникальную. . .
Kafka или Pulsar: Что лучше для потоковой обработки в Java
Javaican 14.03.2025
Среди множества решений для потоковой обработки данных Apache Kafka долгое время удерживала лидирующие позиции, став де-факто стандартом в индустрии. Однако в последние годы всё больше внимания. . .
Создание и использование компонентов в Vue 3
Reangularity 14.03.2025
Компонент в Vue - это автономный блок интерфейса, который содержит собственную разметку, логику и стили. Представьте себе кнопку, форму ввода или даже целую панель навигации - всё это можно оформить. . .
Vue 3: Создаем современное веб-приложение с Composition API
Reangularity 14.03.2025
В фронтенд-разработке Vue 3 выделяется своим прагматичным подходом. В отличие от React с его минималистичной философией "всё — JavaScript" или Angular с его всеобъемлющим корпоративным подходом, Vue. . .
Разработка контекстных меню в iOS
mobDevWorks 14.03.2025
С приходом iOS 13 Apple представила новый API для контекстных меню, который полностью заменил предыдущую технологию 3D Touch peek & pop. Хотя многие разработчики и пользователи испытывают ностальгию. . .
Лучшие практики оптимизации Docker Image
Mr. Docker 13.03.2025
Размер Docker-образа влияет на множество аспектов работы с контейнерами. Чем больше образ, тем дольше его загрузка в реестр и выгрузка из него. Для команд разработки, работающих с CI/ CD пайплайнами,. . .
Вопросы на собеседовании по Docker
Mr. Docker 13.03.2025
Ты сидишь напротив технического специалиста, и вдруг звучит вопрос про Docker Swarm или многоэтапные сборки. Пот на лбу? Не переживай, после этой статьи ты будешь готов ко всему! Эта статья будет. . .
Поиск текста в сносках : замена дефиса на тире или тире на дефис...
РоΜа 13.03.2025
Нужно было найти текст в сносках и заменить. Почему-то метод селекшн не сработал. . . пришлось гуглить. найденный на форумвба код пришлось править. Смысл - заменяет в сносках дефисы и тире на нужные. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru
Выделить код Копировать код Сохранить код Нормальный размер Увеличенный размер