关于代理类的小问题。
我有些不明白Interface::Interface( int v ) :Ptr( new Implementation( v ) ) {} 这段代码中为什么要new? 能否说明一下!谢谢!
Implementation类:
class Implementation
{
public:
Implementation( int v) { value = v; }
int getValue() const { return value; }
private:
int value;
};
Interface类:
class Implementation;
class Interface
{
public:
Interface( int );
int getValue() const;
private:
Implementation *Ptr;
};
对应源文件:
#include "Interface.h"
#include "Implementation.h"
Interface::Interface( int v ) :Ptr( new Implementation( v ) ) {} //<-这个
int Interface::getValue () const
{
return Ptr->getValue( );
}
主函数:
#include <iostream.h>
#include "Interface.h"
void main()
{
Interface i( 5 );
cout<<"Interface contains: "<<i.getValue ()
<<"before setValue"<<endl;
}