简体   繁体   中英

Function with enum return type can not be resolved in a class of C++

  1. My check.h file has an enum as a private variable. I do not know what to do to declare enum as a global entity.
  2. I declare a function in check.cpp with enum return type. But it is giving the error as follows.

    • Multiple markers at this line
    • Type 'TStatus' could not be resolved
    • 'TStatus' does not name a type
    • Member declaration not found

my program is as follows. Can anyone please give me a solution for this.

check.cpp

#include <iostream>
#include "check.h"
using namespace std;


    check::check() { }

    TStatus check::getStatus()
    {
    ......
    }

    check::~check() { }

check.h

#ifndef CHECK_H_
#define CHECK_H_

class check {
private:
    enum TStatus {  ok,sold,defect  };

public:

    check();
    ~check();
    TStatus getStatus();

};

#endif /* CHECK_H_ */

Firstly, you just need to write

check::TStatus check::getStatus()
^^^^^^^

because otherwise the compiler does not know where does TStatus come from.

See full compilable code here: http://ideone.com/l5qxbK

But note also another problem. Your getStatus() is a public function, so you will probably want to call it from outside of a class. But you will not be able to do this because the return type is private , and thus can not be used outside of the class (bar note below). So you will either need to make the enum public , or you can make your getStatus() private if it is not used outside of a class.


Note: you can in fact use getStatus() outside of your class even is your TStatus is private — if you do not use the getStatus() result; see my ideone code linked above. Though in sensible design such call should not have much sense.

Also, see Vlad's answer on how you can use auto to actually store the getStatus() results even is TStatus is private. Though still better is to make TStatus public.

You have to specify class name before name TStatus

check::TStatus check::getStatus()
//...

Here is a demonstrative program

#include <iostream>

class check {
private:
    enum TStatus {  ok, sold, defect };

public:

    check() = default;
    ~check() = default;
    TStatus getStatus() const;
};

check::TStatus check::getStatus() const { return defect; }

int main() 
{
    auto status = check().getStatus();

    std::cout << status << std::endl;
}    

The program output is

2

You have to change your function definition as follows:

check::TStatus check::getStatus()
    {
        return sold;
    }

Demo: http://coliru.stacked-crooked.com/a/0ca5333f3674d39b

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