8.4. Operations on structures¶
Most of the operators we have been using on other types, like
mathematical operators ( +, %, etc.) and comparison operators
(==, >, etc.), do not work on structures by default. It is
possible to define the meaning of these operators for the new type, but
we won’t do that in this book.
A structure can be initialized with a braced list of member values:
struct point {
double x, y;
};
point blank = {3.0, 4.0};
The members are initialized in declaration order: x receives 3.0 and
y receives 4.0. Initialization creates an object; assignment replaces
an existing object's value. In C++20, we can use a braced list in an
assignment as well:
blank = {12.0, 3.2};
We can also copy one structure to another:
1#include <iostream>
2
3struct point {
4 double x, y;
5};
6
7int main() {
8 point p1 = {3.0, 4.0};
9 point p2 = p1; // copy initialization
10 p1 = {12.0, 3.2}; // assignment from a braced list
11 p2 = p1; // copy assignment
12 std::cout << p2.x << ", " << p2.y << '\n';
13}
The output is 12, 3.2. Copying or assigning a point copies the
values of both members.
Q1
Click on all incorrect statements in C++20. Assume point is the structure defined above.
}Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Braced lists work for initialization and assignment. This point type has no equality operator.
Correct.
Q2
Construct a block of code that correctly initializes the instance variables of a structure.
-
double x, y; }; -
blank = 12.0; #distractor -
blank = { 12.0, 3.2 } #distractor -
blank = { 12.0, 3.2 }; -
int blank; #distractor -
int main() { -
point blank; -
struct point { -
}
Q3
Which operators do NOT work on structures. Select all that apply.