static variables !

Hello,

it's very simple but I don't know how to do.
How can i receive in output 1,2,1 ?

I need to create a class I so that output is 1,2,1 with that main. Thanks !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cstdlib>
#include <iostream>

using namespace std;

class I
{
public:

    static int value;
};

int I::value = 1;

using std::cout;

std::ostream& operator<<(std::ostream &strm, const I &i)
{
  return strm;
}
int main()
{
    {
    I i;
    cout << i <<",";
    I j;
    cout << j <<",";
    }
    I k;
    cout <<k;
    
    cin.get();
}
Last edited on
1
2
3
4
5
6
7
8
9
struct I
{
    operator int() const
    {
        static int v = 0 ;
        if( v == 2 ) v = 0 ;
        return ++v ;
    }
};
Your description is very vague.

Presumably the idea is that you want to output the value of I::value via 3 different instances of I, where I::value is a static member, and you need to modify the value of I::value so that the first time you output, it's 1, the second time it's 2, and the third time it's 1 again.

Is that right?

Do you understand what a static member is, and how it differs from a normal member?
Last edited on
Hello mikeboy you're right , that's exactly what I mean.

I did that with your correction but it returns me ,, but it should be 1,2,1

Why ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <cstdlib>
#include <iostream>

using namespace std;

class I
{
    operator int() const
    {
        static int value = 0 ;
        if( value == 2 ) value = 0 ;
        return ++value ;
    }
};

using std::cout;

std::ostream& operator<<(std::ostream &strm, const I &i)
{
  return strm;
}

int main()
{
    {
    I i;
    cout << i <<",";
    I j;
    cout << j <<",";
    }
    I k;
    cout <<k;
    
    cin.get();
}
    
Because your operator<< doesn't actually output anything from i.
ah ! how could it be ?
I think the goal here is not to overload the int cast operator as JLBorges suggested... but instead is to count the number of objects currently in existence. You would do this by incrementing 'value' in each object's constructor, and decrementing it in each object's destructor.
Ah, right, yes - well-spotted, Disch! I wasn't paying attention to those additional scope-defining braces. Largely, because the indentation isn't consistent.
Topic archived. No new replies allowed.