本周终于完成了第一阶段的学习任务(动态库实现+测试环境的搭建)。又陷入了另一个死循环。说到底还是因为过于偏执(之前写过有关C++IDE的搭建的说明。详情可参见 https://my.oschina.net/u/3435444/blog/1476572),可不知为什么sublime text 3 的 格式化代码控件(coolformat)无法正常运行。纠结了三天后,终于大彻大悟。凡事不要依赖于别人,索性回归原始。使用VC++ 6.0 作为 开发IDE。绕了一大圈又回到原点,也许这就是生活吧!闲话少许,书接标题。类继承和对象实例化。本身没有太多的难度,只是从一个java开发者的角度按照C++的模式,实现相关内容。代码如下:
class Box code:
Box.cpp
#include <iostream>
#include "Box.h"
using namespace std;
Box::Box(){
cout << "class box struct method is running\n";
name=(char *)malloc(sizeof(10));
}
Box::~Box(){
cout << "class box destruct method is running\n";
}
Box.h
class Box{
public :
Box();
~Box();
protected:
double length;
char* name;
}
;
class SmallBox code:
SmallBox.cpp
#include <iostream>
#include "SmallBox.h"
using namespace std;
SmallBox::SmallBox(){
cout << "class SmallBox struct method is running\n";
}
SmallBox::~SmallBox(){
cout << "class SmallBox destruct method is running\n";
}
double SmallBox::getLength(void){
return length;
}
void SmallBox::setLength(double len){
length=len;
}
SmallBox.h
#include "Box.h"
class SmallBox:Box{
public:
SmallBox();
~SmallBox();
double getLength(void);
void setLength(double);
}
;
test.cpp
#include <iostream>
#include "SmallBox.h"
using namespace std;
int main(){
cout << "********************************\n";
cout << "main method is running !\n";
SmallBox *obj =new SmallBox();
obj->setLength(10.1);
cout << "SmallBox length is "<< obj->getLength() << "\n";
delete(obj);
cout << "********************************\n";
return 0;
}
总结:
已上内容通过SmallBox 继承Box ,在main方法中,初始化SmallBox 并调用 相关方法的demo。例子很简单,关键是实现思路。如有不妥之处还请赐教。