I am still learning C++, and I have never really created my own namespaces before. I was experimenting with them and while I got most things to work, there’s one thing that I still can’t seem to do. I would like to be able to call a static method within a class without typing something like NameOfClass::method. Here is what I thought the code should look like, but it fails to compile:
File A.h,
namespace Test { class A { public: static int foo() { return 42; } }; }
File main.cpp,
#include <iostream> #include 'A.h' using namespace std; using namespace Test::A; int main() { cout << foo() << endl; return 0; }
The compiler gives me:
main.cpp:6: error: ‘A’ is not a namespace-name main.cpp:6: error: expected namespace-name before ‘;’ token main.cpp: In function ‘int main()’: main.cpp:10: error: ‘foo’ was not declared in this scope
Is it possible to do what I am trying to do without typing A::foo?
There is no way around it you need to specify the class name for static methods.
Then: