Person.h
#include <string>
#include <memory>
using namespace std;
class PersonImpl; // Person实现类的前置声明
class Person
{
public:
Person(const string& name);
string getname() const;
private:
tr1::shared_ptr<PersonImpl> pImpl; // 指针,指向实现物,或者PersonImpl* pImpl
string name;
};
Person.cpp
#include "stdafx.h"
#include "Person.h"
#include "PersonImpl.h"
Person::Person(const string& name) : pImpl(new PersonImpl(name))
{
this->name = name;
}
string Person::getname() const
{
return pImpl->getname();
}
#include <string>
#include <iostream>
using namespace std;
class PersonImpl
{
public:
PersonImpl(const string& name)
{
this->name = name;
//cout << "Impl" << endl;
}
string getname() const;
private:
string name;
};
PersonImpl.cpp
#include "stdafx.h"
#include "PersonImpl.h"
string PersonImpl::getname() const
{
return this->name;
}
main.cpp
#include "stdafx.h"
#include "Person.h"
#include <memory>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// Handle Class
Person p("Yerasel");
cout << p.getname() << endl;
return 0;
}
以上方法是pImpl方法,它是微软的Herb Sutter提出来的,该方法是为了尽量减小接口和实现之间的耦合,以避免接口改动对程序重新编译等带来的影响。简单来说,如果你的大型程序因为复杂的头文件包含关系,使得你对某头文件的某小改动可能引起的巨大编译时间成本望而生畏,那么你需要用pImpl方法来改善这种处境。
抽象类(abstract class)
抽象类是指含有纯虚函数的类(至少有一个纯虚函数, 纯虚函数 virtual void f() = 0; ),该类不能创建对象(抽象类不能实例化),但是可以声明指针和引用,用于基础类的接口声明和运行时的多态。
抽象类中,既可以有抽象方法,也可以有具体方法或者叫非抽象方法。抽象类中,既可以全是抽象方法,也可以全是非抽象方法。一个继承于抽象类的子类,只有实现了父类所有的抽象方法才能够是非抽象类。
接口
接口是一个概念。它在C++中用抽象类来实现,在C#和Java中用interface来实现。
接口是专门被继承的。接口存在的意义也是被继承。和C++里的抽象类里的纯虚函数是相同的。不能被实例化。
java中的接口只能含有方法,不能有成员变量,而c++的抽象类中可以含有成员变量。
定义接口的关键字是interface,例如:
public interface MyInterface{
public void add(int x,int y);
public void volume(int x,int y,int z);
}
通过子类继承抽象类(接口),来进行实例化。
Person2.h
#ifndef REAL2_H
#define REAL2_H
#include "Person2.h"
#include <iostream>
using namespace std;
class RealPerson2 : public Person2
{
public:
RealPerson2(const string& name)
:Person2(name), thename(name)
{
}
virtual ~RealPerson2(){}
string getname() const
{
return this->thename;
}
private:
string thename;
};
#endif
main.cpp
#include "Person.h"
#include <memory>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// Interface Class
tr1::shared_ptr<Person2>p2 = (Person2::create("jandosim"));
cout << p2->getname() << endl;
return 0;
}
附注,shared_ptr示例
//工厂模式
class abstract
{
public:
virtual void f()=0;
virtual void g()=0;
protected:
virtual ~abstract(){}
};
class impl:public abstract
{
public:
virtual void f()
{
cout << "class impl f" << endl;
}
virtual void g()
{
cout << "class impl g" << endl;
}
};
tr1::shared_ptr<abstract> create()
{
return tr1::shared_ptr<abstract>(new impl);
}
int _tmain(int argc, _TCHAR* argv[])
{
tr1::shared_ptr<abstract> a = create();
a->f();
a->g();
return 0;
}
原文地址:http://blog.youkuaiyun.com/ozwarld/article/details/7101974