I’ve read all the suggestions I’ve found in the following links
- c++ typedef another class's enum?
- http://forums.devarticles.com/c-c-help-52/how-to-use-enum-when-it-is-in-another-class-17773.html
- http://forums.codeguru.com/showthread.php?t=435215
- How do I use the Enum value from a class in another part of code?
but still wasn’t able to find a solution to my problem:
I need to construct an object of
class A(whose constructor expects as an input
parameter an enumerative type of that class) from inside a function of an object ofclass B
Here are the code snippets:
File A.h:
Class A{
public:
enum FileType{TEXT, BIN};
/*! This constructor initializes the data from a given file
* (binary, text, image).
*/
A(const std::string& filename, FileType type);
}
File A.cpp:
A::A(const std::string& filename, FileType type){
...
}
File B.h:
Class B{
private:
A objectOfClassA;
public:
enum FileType{TEXT = A::FileType::TEXT, BIN = A::FileType::BIN}; //<----THIS IS NOT WORKING!
foo_func(const std::string& filename, FileType type);
}
File B.cpp:
void B::foo_func(const std::string& filename, FileType type){
this->objectOfClassA(filename, type); //should construct an object of class A
... //do stuff with objectOfClassA
}
File main.cpp:
int main(int argc, char** argv) {
B objectOfClassB;
objectOfClassB.foo_func("file_path", foo_func.TEXT);
}
By trying to run main program I get this error from compiler in the B.cpp file at line of function foo_func:
no match for call to ‘(A)
(std::basic_string, B::FileType&)’
which means that I’m not using the correct enum type to call A class constructor, but how can I fix this?
What am I doing wrong?
B::FileTypeandA::FileTypeare different types. You need totypedef A::FileType FileTypeinside B to alias the types correctly so they are interchangeable. OtherwiseB::FileTypeis an enum which is structurally the same asA::FileType, but unrelated in the type system. This answers your primary question.Fixing this still won’t permit your code to compile, however, and this is not what the error is complaining about.
objectOfClassA is already constructed inside foo_func. Calling
this->objectOfClassA(filename, type)is an attempt to use the overloaded () operator on the object; this operator does not exist so the code cannot compile. You can only construct objectOfClassA via B’s constructor using initializer notation, e.g.Then in main you would do this:
Step through in the debugger to see the control flow.