#include <iostream>
#include <string>
using namespace std;
class Weapon
{
public:
void dispWeapon();
private:
string weapName;
protected:
};
void Weapon::dispWeapon()
{
weapName = "knife";
cout << weapName << endl;
}
class Character
{
public:
void aFunc();
private:
Weapon weapon;
protected:
};
void Character::aFunc()
{
cout << "aFunc\n";
}
int main()
{
Character character;
character.aFunc();
character.weapon.dispWeapon(); //I know this is wrong but how am I supposed to access
//class Weapon through class Character
return 0;
}
error C2248: 'Character::weapon' : cannot access private member declared in class 'Character'
see declaration of 'Character::weapon'
see declaration of 'Character'
isn't legal because you defined weapon as private. Move the "Weapon weapon;" declaration to Character's public members and it will work just fine. If you want to leave it in private then you need to make an accessor (which would probably end up returning a pointer to weapon that you could then use to make function calls).
Last edited by dandymcgee on Mon Jun 29, 2009 4:12 pm, edited 2 times in total.
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches!
I am assuming I did it right I guess.... :|[/quote]
Yup, that looks about right. If it compiled then I suppose it works. ;)[/quote]
It does work and displays what's inside the functions
hmm weird I have never gotten around to this if this
stuff is super common...:(. Thanks though I believe
I got this down now.
This is bad because it makes a copy of the weapon and returns it. You don't want to make a copy, this is slow. Return a const reference or a const pointer. You might be returning a const copy, I'm not sure, I have to brush up on the different locations of the const keyword. I think declaring the function as