Problem with class...

I'm trying to create my first class but I keep getting an error at compile for each of the 4 shapes in the class member, shape.
Error
1
2
3
4
documents\visual studio 2008\projects\template\template\template.cpp(47) : error C2864: 'shapes::circle' : only static const integral data members can be initialized within a class
1>c:\users\\\documents\visual studio 2008\projects\template\template\template.cpp(47) : error C2864: 'shapes::square' : only static const integral data members can be initialized within a class
1>c:\users\\\documents\visual studio 2008\projects\template\template\template.cpp(47) : error C2864: 'shapes::triangle' : only static const integral data members can be initialized within a class
1>c:\users\\\documents\visual studio 2008\projects\template\template\template.cpp(47) : error C2864: 'shapes::rectangle' : only static const integral data members can be initialized within a class



Code:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Template.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}

class shapes {
public:
	void getShape(int getSelect) {
		switch (getSelect) {
			case 1 :
				cout << "You selected " << circle << endl;
				break;
			case 2 :
				cout << "You selected " << square << endl;
				break;
			case 3 :
				cout << "You selected " << triangle << endl;
				break;
			case 4 :
				cout << "You selected " << rectangle << endl;
				break;
			default : 
				cout << "Select circle, square, triangle, or rectangle." << endl;
		}
	}

	int menu()
	{
		cout << "1.) Circle" << endl;
		cout << "2.) Square" << endl;
		cout << "3.) Triangle" << endl;
		cout << "4.) Rectangle" << endl;
		int getSelect;
		cin >> getSelect;
		return getSelect;
	}

private:
	string circle = "Circle", square = "Square", triangle = "Triangle", rectangle = "Rectangle";
};


int main()
{
	cout << "Please select a shape: " << endl;
	int userShape;
	shapes s;
	userShape = s.menu();
	s.getShape(userShape);
	return 0;
}
You aren't allowed to define member variables in this way unless they are const static (meaning they can't change, and all class objects share the same values).

1
2
 private:
	string circle = "Circle", square = "Square", triangle = "Triangle", rectangle = "Rectangle";


Normally constructors are used when you want member variables to have default values when you first create the object.

1
2
3
4
shapes::shapes()
{
     circle = "Circle";
}

http://www.cplusplus.com/doc/tutorial/classes/
Last edited on
Bollocks! ok, Thanks!
Last edited on
Topic archived. No new replies allowed.