Answer the question
In order to leave comments, you need to log in
Structure - what is it?
In the book, I got to classes, but as far as I remember, when I read Prata's book a long time ago, everything was gradual there and classes were declared using the word class, and in Lippmann's textbook, immediately struct without any explanation. As a result, after reading, I received the following code:
struct Sales_data
{
Sales_data() = default;
Sales_data(const string &s) : bookNo(s) {}
Sales_data(const string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) {}
Sales_data(istream &);
//другие члены как прежде
string isbn() const
{
return bookNo;
}
Sales_data &combine(const Sales_data &);
double avg_price() const;
string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
Sales_data total;
Sales_data trans;
Answer the question
In order to leave comments, you need to log in
Structures in C++ are equivalent to classes, the default access modifier in structures is public, in classes it is private.
As sdxq mentioned , in fact the structs and classes are identical except for the default access modifier. But historically it so happened that structures are used only to store any data, without operations. For example,
struct Point
{
int x;
int y;
}
If I specify these constructors in the class before the public modifier, how can I use them at all?
Structs are used to create composite data types. Previously (in C) they were limited only to data, but then (in C ++) they added the creation of operations on them for these composite data.
If you made, for example, a point structure, then it would be nice if it could calculate the distance from itself to another point of the same type. If earlier it was necessary to write a separate function, now you can shove this function directly into the structure.
The same goes for initialization: if earlier it was possible to initialize in one way, now you can do different ways of initialization by creating different constructors.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question