简体   繁体   中英

C++ begineer : using namespace error

I am really new in C++, and I can not solve the compilation error below.

data_structure.h

#include <stdint.h>
#include <list>

namespace A {

        class B {
            public:

            bool        func_init(); // init
            };

};

data_structure.cpp

#include "data_structure.h"

using namespace A;

bool B::func_init(){

    std::cout << "test init" << std::endl;
    return true;

}

main.cpp

#include    <iostream>
#include    "data_structure.h"

using namespace A;

int main( int argc, char **argv ) {

    A::B s;
    s.func_init();

    return 0;
}

I have an error as the following

undefined reference to `A::B::func_init()'

Please kindly advice why I can not get the func_init, eventhough it is declared as public? I have put also the correct namespace there.

Would appreciate for any response.

这是一个链接器错误,因此您可能没有编译所有源文件,或将它们链接在一起,或者使用C编译器(我看到您的文件具有扩展名.c ,一些编译器将它们视为C源代码) )。

g++ main.cpp data_structure.cpp -o test should do it.

However I did need to add #include <iostream> to your data_structure.cpp file to resolve

data_structure.cpp: In member function ‘bool A::B::func_init()’:
data_structure.cpp:7:5: error: ‘cout’ is not a member of ‘std’
data_structure.cpp:7:33: error: ‘endl’ is not a member of ‘std’

and make it compile.

The definition of a function has to be in the namespace that declares the function. A using declaration just pulls in names from the namespace; it doesn't put you inside it. So you have to write data_structure.cpp like this:

#include "data_structure.h"
#include <iostream>

namespace A {
bool B::func_init() {
    std::cout << "test init" << std::endl;
    return true;
}
}

Or, if you prefer, you can use the namespace name explicitly in the function definition:

bool A::B::func_init() {
    std::cout << "test init" << std::endl;
    return true;
}

Have you tried not putting

using namespace A;

in your data_structure.cpp file and instead putting:

#include "data_structure.h"

bool A::B::func_init() {
   std::cout << "test init" << std::endl;
   return true;
}

I have the feeling that when you use using namespace A; doesn't let you append function definitions to the namespace, but only tells the compiler/linker where to look for Types or Functions...

Another theory: Have you tried nesting your CPP code in the same namespace?

#include "data_structure.h"

namespace A {
   bool B::func_init() {
      std::cout << "test init" << std::endl;
      return true;
   }
}

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