namespace question

error: 'a' in namespace 'Rectangle' does not name a type
error: 'b' in namespace 'Rectangle' does not name a type

But 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
#include <iostream>

using namespace std;

namespace Circle
{
    const double pi = 3.14;
    double r = 100;
    double Area() { return (r*r*pi); }
}

namespace Rectangle
{
    double a, b;
    double Area() { return (a*b); }
}

    Rectangle::a = 20;
    Rectangle::b = 30;

int main()
{
    cout << "Circle:   " << Circle::Area() << endl;
    cout << "Rectangle:" << Rectangle::Area() << endl;

    return 0;
}
Put it in main

1
2
3
4
5
6
7
8
9
10
11
int main()
{

	Rectangle::a = 20;
	Rectangle::b = 30;

	cout << "Circle:   " << Circle::Area() << endl;
	cout << "Rectangle:" << Rectangle::Area() << endl;

	return 0;
}
@fx11

Move lines 18 and 19, to inside main().
Hi! Thanks for the answers.

My question is why does it not work in my example?

I know it works inside main().
I know it works inside main().

But why does it not work outside main?
A variable can be initialized when it is created, but it cannot be changed outside a function.
I think I see. Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int x = 10;  //declaration and initialization
int y;       //declaration

y = 20;      //assignment NOT ALLOWED here

int main()
{
    cout << "x:" << x << endl;
    cout << "y:" << y << endl;

    return 0;
}
error: 'y' does not name a type
Topic archived. No new replies allowed.