2014-06-05 42 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