Calling Variable from other classes

How do I call a variable from one class to use it in another? The code is a bit off but basically im trying to take a variable from the class and use it in my main.

my.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef MY_H
#define MY_H
#pragma once
class my
{
public:
	my(void);
	private:
		static int hp;

};

#endif 


my.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include "my.h"
using namespace std;


my::my(void)
{
}


source.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include "my.h"
using namespace std;


int main(){

hp - 35;

cout << hp <<endl;
}
closed account (j3Rz8vqX)
http://www.cplusplus.com/doc/tutorial/classes/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include "my.h"
using namespace std;


int main(){
my anObject;
anObject.addhp(-35);

cout << anObject.gethp() <<endl;
}

1
2
3
4
5
6
7
8
9
10
class my
{
public:
    my(){hp=0;}
    void addhp(int i){hp=hp+i;}
    void gethp(){return hp;}
private:
    static int hp;

};
I am getting few errors in that code.

For
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef MY_H
#define MY_H

class my
{
public:
    my(){hp=0;}
    void addhp(int i){hp=hp+i;}
    void gethp(){return hp;}
private:
    static int hp;

};
#endif

in the line.
    void gethp(){return hp;}


I am being told that my return value does not match my function type.

and in main

1
2
3
4
5
6
7
8
9
10
11

int main(){
my anObject;
anObject.addhp(-35);

cout<<anObject.gethp()<<endl;
}

in the line

cout<<anObject.gethp()<<endl;


I am beint told. "No operator "<<" matches these operands." Im not sure about the return hp line. But the last line seems correctly written to me.
You have your function returning a 'void', you should be returning an integer. Also, a little thing: Why is your 'hp' variable static? And if you did want it to be static (for some reason), you should make your getHP and addHP functions static as well (considering all they are doing is accessing a static variable).
I think I was fooling around with friend classes for the same problem and just forget to switch it back.
I am still struggling with the output line. I'm not really sure what it is asking.
NT3 already explained that gethp needs to return an integer.

In my.h at line 9, you're attempting to return an integer, but the function is declared as void.

main.cpp line 11, the compiler is complaning because you're trying to print a void. There is no << operator that can print a void. Change gethp to return an int and this error will go away.
Last edited on
closed account (j3Rz8vqX)
I was coding on the fly, the correct function declaration would be:
int gethp(){return hp;}
Topic archived. No new replies allowed.