c++ classes Help

Hello Evry one :) Im new in c++
how can i print x value ?? look to the Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
using namespace std;

class ali{
    public:
    int x=55;
       void alif(){
         cout<<x;
       }
};
int main()
{
system("color a");
ali alio;
alio.alif();
    return 0;
}
Change "return 0;" to "return 1". Return 0 won't return a value.
doesntWork.cpp:9: error: ISO C++ forbids initialization of member 'x'
doesntWork.cpp:9: error: making 'x' static
doesntWork.cpp:9: error: ISO C++ forbids in-class initialization of non-const static member 'x'


You are not allowed to initialize x in the class definition. To initialize x, you either need a function to set the value of x (often referred to as a "setter") or a constructor which sets x to a value.

See:

http://cplusplus.com/doc/tutorial/classes/

For setters, see the first example of the CRectangle class, the function you're interested in is called set_values (adjust it accordingly to fit your code).

For constructors, see the section on constructors and destructors.


Change "return 0;" to "return 1". Return 0 won't return a value.


That makes no sense, return 0; returns 0, return 1; returns 1. See, they both return a value.

The return call you refer to returns a value to the OS (see link below) and is used to indicate successful termination of the program. It is also the return from the main function and is completely irrelevant to the OP's question.

http://www.cplusplus.com/forum/beginner/24461/
Danny Toledo wrote:
You are not allowed to initialize x in the class definition.
It is allowed in C++11.

@Ali Tajiri
What error message do you get?
Assuming that you aren't in C++11, you could do this:
1
2
3
4
5
6
7
class ali{
public:
  static const int x = 55;
  void alif() {
    cout << x;
  }
};

or this:
1
2
3
4
5
6
7
8
class ali{
public:
  int x;
  ali() : x(55) {}
  void alif() {
    cout << x;
  }
};
Last edited on
cbutler wrote:

Change "return 0;" to "return 1". Return 0 won't return a value.


return 0 is the correct way to end your main() program function. It's the same as saying return EXIT_SUCCESS which is the proper, portable way for your program to communicate exit status to the OS. return 1 indicates your program failed in some way and the OS should inform the user.
Topic archived. No new replies allowed.