S
S
sabn1k2016-02-14 10:45:27
C++ / C#
sabn1k, 2016-02-14 10:45:27

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;

Lord, what is this? Clarify please.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
sdxq, 2016-02-14
@sdxq

Structures in C++ are equivalent to classes, the default access modifier in structures is public, in classes it is private.

K
Kirill Romanov, 2016-02-14
@Djaler

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;
}

R
res2001, 2016-02-14
@res2001

If I specify these constructors in the class before the public modifier, how can I use them at all?

This technique is used to create classes that can only be instantiated by friends or static public methods of a class, for example to ensure that only one class object is created (singleton pattern). Usually, in addition to constructors, a destructor is also placed in a private section, and a friend or static method is also made to obtain an instance of the class and to destroy it.
In addition, the constructor and destructor can be placed in the protected section of the class - then only descendants can create instances of the class.

A
abcd0x00, 2016-02-20
@abcd0x00

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 question

Ask a Question

731 491 924 answers to any question