简体   繁体   中英

Error when using public member function to access private member variable: Variable “was not declared in this scope”

Update for anyone having trouble returning multidimensional arrays

Further reading: Returning multidimensional array from function

I've declared a static int variable in my header. I've defined it in the .cpp file (Implementation file?), as shown with the relevant code below...

Card.h

#ifndef CARD_H
#define CARD_H

class Card {
private:
    static int  _palette[][3];
public:
    static int  palette();
};

#endif /* CARD_H */

Card.cpp

int Card::_palette[][3]=    {
    {168, 0,   32},
    {228, 92,  16},
    {248, 216, 120},
    {88,  216, 84},
    {0,   120, 248},
    {104, 68,  252},
    {216, 0,   204},
    {248, 120, 248}
};

static int palette(){
    return _palette;
}

But when I compile, I get this error:

..\source\src\Card.cpp: In function 'int palette()':
..\source\src\Card.cpp:42:9: error: '_palette' was not declared in this scope
  return _palette;

Shouldn't my accessor function palette() be able to get the value of private member _palette ?

You forgot the Card::

int (*Card::palette())[3]{
    return _palette;
}

You shouldn't have static in the method definition. Also, you're trying to return an int[][] when you should return an int .

Change your class to this:

class Card {
private:
    static int  _palette[][3];
public:
    static int  (*palette())[3];
};

Firstly, the method name is Card::palette , not just palette . And Card::palette is what you should use in the method definition.

Secondly, static method definition is not supposed to include the keyword static .

Thirdly, how are you expecting to be able to return an array as an int value??? Given the declaration of your _palette array, to return it from a function you'd have to use either int (*)[3] return type or int (&)[][3] return type

int (*Card::palette())[3] {
    return _palette;
}

or

int (&Card::palette())[][3] {
    return _palette;
}

And a typedef can make it more readable.

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