2013-04-10 148 views
2

我真的是新的C++,我無法解決下面的編譯錯誤。C++ begineer:使用命名空間錯誤

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; 
} 

我有一個錯誤,如下

未定義的參考`A :: B :: func_init()」

敬請指教,爲什麼我不能得到func_init,儘管它已經被聲明爲public?我也在那裏提供了正確的命名空間。

希望對此有所迴應。

回答

5

這是一個鏈接器錯誤,所以你可能不會編譯所有的源文件,或者將它們連接在一起,或者對C編譯器做一些奇怪的使用(我看到你的文件的擴展名爲.c,有些編譯器把它們當作是C-源)。

+0

我的錯,那是CPP文件從一開始,不是c文件。但我仍然有compliation – xambo 2013-04-10 14:46:32

+0

@xambo這個問題你怎麼編譯? – 2013-04-10 14:48:31

+0

g ++ main.cpp -o test – xambo 2013-04-10 14:51:03

0

您是否嘗試過不把

using namespace A; 

在data_structure.cpp文件,而不是把:

#include "data_structure.h" 

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

我有一種感覺,當你使用using namespace A;不讓你附加的功能定義到命名空間,但只告訴編譯器/鏈接器在哪裏尋找類型或函數...

另一個理論: 你是否嘗試過在相同的命名空間中嵌套你的CPP代碼?

#include "data_structure.h" 

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

g++ main.cpp data_structure.cpp -o test應該這樣做。

但是我確實需要添加#include <iostream>您data_structure.cpp文件來解決

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’ 

,並使其編譯。

1

函數的定義必須位於聲明該函數的名稱空間中。一個using聲明只是從名字空間中取出名字;它不會把你放進去。所以,你必須寫data_structure.cpp這樣的:

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

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

或者,如果你願意,你可以在函數定義明確使用命名空間名稱:

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

+1這是我的理解,雖然我確實設法使用g ++ 4.4.3編譯等價於OP的代碼,但我真的不希望這樣做。 – juanchopanza 2013-04-10 15:26:23