Advertisement

Code Error

Started by April 02, 2002 11:17 PM
9 comments, last by GoldenOne 22 years, 9 months ago
What in the world is wrong with my code? I want to see health.
  
#include <iostream>
using namespace std;

const int MAXCHAR = 50;

class terran 
	{
	private: 
		char unitname[MAXCHAR];
		int health;
	public:
		terran();
		terran(char * unitname, int health);
		void show();
	};

int main()
	{
	terran obj1("hey", 10);
	cout << obj1.health;
	return 0;
	}

void terran::show()
	{
	cout << obj1.health;
	}
  
health is a private member so you cant access it through cout.

if you want to see health try

obj1.show();
Why is 99% of the Comp Sci population guys, and the other 1% not female? ;/
Advertisement
and in your terran:show() it should be

cout << health;

not obj1.health
Why is 99% of the Comp Sci population guys, and the other 1% not female? ;/
int main()
{
terran obj1("hey", 10);
cout << obj1.health;
return 0;
}

Your class states that health is private and you even made a member function to print out the health but there''s a problem in it as well

void terran::show()
{
cout << obj1. health;
}

You don''t need to show an instance of the class since you defining a member of the class. You should use your now fixed show function instead of the call to the private member.

int main()
{
terran obj1("hey", 10);
obj1.show();
return 0;
}

Invader X
Invader''s Realm
in your show function, don''t use obj1.health. just use health, like cout << health.
AcidJazz.... you suck

Invader X
Invader''s Realm
Advertisement
I remember starting like you once upon a time, if you ever need some help just IM me

AIM - AcidJazz13
ICQ - 7060088
MSN - acidjazz90@rgv.rr.com

i''d be happy to help
Why is 99% of the Comp Sci population guys, and the other 1% not female? ;/
Well, first of all, you cant directly access a class''s private member date, you need to call the show method.
Secondly, you haven''t defined your constructor with arguments, so it has no idea that the number you put in is going into Health.

Thirdly, your show function has no idea what obj1 is, as it is outside the scope of yoru main function. Use the goo old referential self pointer:

#include <iostream>using namespace std;const int MAXCHAR = 50;class terran 	{	private:	char unitname[MAXCHAR];	int health;	public:	terran();	terran(char * unitname, int health);	void show();};int main()	{	terran myterran;	myterran.show();	return 0;	}void terran::show()	{	cout << this->health;	}  terran::terran(){}terran::terran(char * unitname, int health){} 

Invader, ohhh yea Err so i made a mistake, and i just reread what i wrote, it didnt even make sense "You can''t use health through cout?" bah ;/

Why is 99% of the Comp Sci population guys, and the other 1% not female? ;/
I was refering to the time difference:

You - 12:25:25 AM
Me - 12:25:27 AM

Bah!

Invader X
Invader''s Realm

This topic is closed to new replies.

Advertisement