2014-06-05 76 views
1

我是新來的代理類的概念,在C++中,當我嘗試一個程序,我有錯誤,如未定義的引用功能。我不知道程序中哪裏出了問題,請幫我糾正這些錯誤。未定義的引用功能接口::接口(int)

undefined reference to `Interface::Interface(int)' 
undefined reference to `Interface::getValue() const' 
undefined reference to `Interface::setVale(int)' 
undefined reference to `Interface::~Interface()' 

的代碼如下

Implementation.h

#ifndef IMPLEMENTATION_H_INCLUDED 
#define IMPLEMENTATION_H_INCLUDED 

class Implementation 
{ 
public: 
    Implementation(int v):value (v){} 
void setValue(int v) 
{ 
    value=v; 
} 
int getValue()const{ 
    return value; 
} 
private: 
    int value; 
}; 

#endif // IMPLEMENTATION_H_INCLUDED 

Interface.h

#ifndef INTERFACE_H_INCLUDED 
    #define INTERFACE_H_INCLUDED 

    class Implementation; 
    class Interface 
    { 
     private: 
     Implementation *ptr; 
    public: 
     Interface(int); 
     void setValue(int); 
     int getValue() const; 
     ~Interface(); 

    }; 

    #endif // INTERFACE_H_INCLUDED 

Interface.cpp

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

Interface::Interface(int v):ptr(new Implementation(int v)) 
{ 
} 

void Interface::setValue(int v) 
{ 
    ptr->setValue(v); 
} 
int Interface::getValue()const 
{ 
    return ptr->getValue(); 
} 

Interface::~Interface() 
{ 
    delete ptr; 
} 

和這裏有雲的主要功能 MainFunction.cpp

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

int main() 
{ 
    Interface i(2); 

    cout<<"Interface Contains:"<<i.getValue()<<"before setValue"<<endl; 

    i.setValue(10); 

    cout<<"Interface contains:"<<i.getValue()<<"after setValue"<<endl; 
    return 0; 
} 
+6

你似乎忘了將Interface.cpp添加到你的版本。 –

+0

你可以顯示你的編譯命令行 – quantdev

+2

在旁邊註釋...'{Interface x(1);界面y = x; } //哎呀,雙刪除。 –

回答

0

編譯使用命令g++ MainFunction.cpp Interface.cpp也接口的構造函數的定義應該是Interface::Interface(int v):ptr(new Implementation(v))

+0

好吧,我從定義中刪除了int。再次發生了同樣的錯誤。如果我在我的MainFunction.cpp中包含Interface.cpp而不是Interface.h,那麼運行良好,但是如果我使用Interface.h,則會引發錯誤。爲什麼這樣? – user3709600

+0

@ user3709600在編譯過程中是否包含了Interface.cpp,可否請您展示您的命令以編譯上述程序。 – EmptyData

+0

@ user3709600當你在MainFunction.cpp中包含Interface.cpp時,這意味着你在主文件中包含了寫在Interface.cpp中的代碼,因此Interface.cpp包含了Interface.h,所以類和它的函數定義都會包括在你編譯工作的主文件中。 – EmptyData