简体   繁体   中英

cannot access private member declared in class 'Soldier'

I'm new to OOP and I do not understand how to pass arguments to classes.

The class' declaration:

class Soldier
{
    Soldier(int SetHealth, int SetStrength);

private:
    int health;
    int strength;

public:
    void attacked();
    void healed();
    int getHealth();
    int getStrength();
};

Definition of the constructor:

    Soldier::Soldier(int SetHealth, int SetStrength):
        health(SetHealth),
        strength(SetStrength)
    {

    }

When I try passing arguments to the class it says this:

    1>------ Build started: Project: ConsoleApplication6, Configuration: Debug Win32 ------
    1>  ConsoleApplication6.cpp
    1>c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp(11): error C2248: 'Soldier::Soldier' : cannot access private member declared in class 'Soldier'
    1>          c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\soldier.h(7) : see declaration of 'Soldier::Soldier'
    1>          c:\users\user\documents\visual studio 2012\projects\consoleapplication6\consoleapplication6\soldier.h(6) : see declaration of 'Soldier'
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Your constructor is private (just as the error message says). By default, every member of a Class is private if you don't specify an access level.

The constructor that you have defined has a access level of

private

By default if one does not mention anything, the access level is private So change it to public for access.

A class's members are implicitly private unless you change the access level to public or protected , so Soldier::Soldier(int SetHealth, int SetStrength); is private - ergo you can't access it.

将构造函数声明更改为此public Soldier(int SetHealth, int SetStrength);

People have already answered this now, but explicitly:

class Soldier
{
private:
    int health;
    int strength;

public:
    Soldier(int SetHealth, int SetStrength);

    void attacked();
    void healed();
    int getHealth();
    int getStrength();
};

BTW What are attached and healed going to do? They take no parameters and return nothing. Odd.


Edit (in light of recent down vote):

Moving the constructor to the public "section", makes it public . Things start off as private until you say otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM