Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 99 lines (79 sloc) 2.097 kb
3b1e741 @gpdowning another commit
authored
1 // ---------------------
2 // InstanceVariables.c++
3 // ---------------------
4
5 #include <cassert> // assert
6 #include <iostream> // cout, endl
7
8 template <typename T>
9 struct A {
10 // T v = 2; // error: ISO C++ forbids initialization of member "v"
11 T v;
12 T w;};
13
14 template <typename T>
15 struct B {
16 T v;
17 const T cv;};
18
19 int main () {
20 using namespace std;
21 cout << "InstanceVariables.c++" << endl;
22
23 {
24 A<int> x;
25 // assert(x.v == 0); // undefined
26 // assert(x.w == 0); // undefined
27
28 A<int> y = {};
29 assert(y.v == 0);
30 assert(y.w == 0);
31
32 A<int> z = {2};
33 assert(z.v == 2);
34 assert(z.w == 0);
35
36 A<int> t = {2, 3};
37 assert(t.v == 2);
38 assert(t.w == 3);
39
40 // const A<int> x; // error: uninitialized const "x"
41 // assert(A<int>::v == 2); // error: invalid use of non-static data member "A<int>::v"
42 }
43
44 {
45 const A<int> x = {2, 3};
46 A<int> y = x; // A<int> y(x);
47 assert(y.v == 2);
48 assert(y.w == 3);
49 assert(&x.v != &y.v);
50 assert(&x.w != &y.w);
51
52 {
53 const A<int> x = {2, 3};
54 A<int> y = {4, 5};
55 y = x;
56 assert(y.v == 2);
57 assert(y.w == 3);
58 assert(&x.v != &y.v);
59 assert(&x.w != &y.w);
60 }
61
62 {
63 // B<int> x; // error: structure "x" with uninitialized const members
64 // B<int> y = {}; // error: uninitialized const member "B<int>::cv"
65 // B<int> z = {2}; // error: uninitialized const member "B<int>::cv"
66 B<int> t = {2, 3};
67 assert(t.v == 2);
68 assert(t.cv == 3);
69 }
70
71 {
72 const B<int> x = {2, 3};
73 assert(x.v == 2);
74 assert(x.cv == 3);
75
76 B<int> y = x; // B<int> y(x);
77 assert(y.v == 2);
78 assert(y.cv == 3);
79
80 assert(&x.v != &y.v);
81 assert(&x.cv != &y.cv);
82 }
83
84 {
85 const B<int> x = {2, 3};
86 assert(x.v == 2);
87 assert(x.cv == 3);
88
89 B<int> y = {4, 5};
90 assert(y.v == 4);
91 assert(y.cv == 5);
92
93 // y = x; // error: non-static const member "const int B<int>::cv", can't use default assignment operator
94 }
95 }
96
97 cout << "Done." << endl;
98 return 0;}
Something went wrong with that request. Please try again.