我正在学习C++通过C++入门书。它是关于创建一个带有一些对象的类。我真的不知道该怎么做才能让这个程序开始工作。我正在使用CODEBLOCKS 13.12,我复制了以下代码:
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item book;
//read ISBN, number of copies sold, and sales price
std::cin>>book;
//write ISBN, number of copies sold, total revenue, and average price
std::cout<<book<<std:endl;
return 0;
}在此之后,出现了一个错误(我不完全理解它是什么,因为只有这个代码行右边的小红方:#include "Sales_item.h" )
我尝试创建了一个类(作者不要求这样做),并创建了两个文件:
Sales_item.h.h
#ifndef SALES_ITEM_H_H
#define SALES_ITEM_H_H
class Sales_item.h
{
public:
Sales_item.h();
virtual ~Sales_item.h();
protected:
private:
};
#endif // SALES_ITEM_H_H第二个是:
Sales_item.h.cpp
#include "Sales_item.h.h"
Sales_item.h::Sales_item.h()
{
//ctor
}
Sales_item.h::~Sales_item.h()
{
//dtor
}作者要求将以下代码复制到当前目录中。但是,我不知道他用“当前目录”是什么意思。
/* 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
// 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
Sales_item(): units_sold(0), revenue(0.0) { }
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
unsigned units_sold;
double revenue;
};谢谢!
发布于 2014-05-30 04:13:40
作者“要求”您将代码复制到Sales_item.h文件中。请删除您自己的类Sales_item.h,包括Sales_item.h.h和Sales_item.h.cpp,重新开始使用作者的Sales_item.h文件,并在需要时创建Sales_item.cpp。
类名是Sales_item,而不是Sales_item.h。当前目录表示代码所在的位置。
发布于 2014-05-30 06:18:38
在一个文件中编写所有代码通常非常麻烦。因此,C++允许您将代码分解到不同的文件中,然后将其包含在您需要的文件中。
#include "Sales_item.h"只是告诉编译器在当前程序中包含Sales_item.h中的所有代码。
您得到错误的原因是您的计算机中没有Sales_item.h文件!
您可以获得Sales_item.h和书籍这里可能需要的其他资源文件。
将Sales_item.h复制到与代码相同的目录中。
在你复制资源之前,试着自己写这些例子。
https://stackoverflow.com/questions/23946782
复制相似问题