C++ 实践之类继承与对象实例化

   本周终于完成了第一阶段的学习任务(动态库实现+测试环境的搭建)。又陷入了另一个死循环。说到底还是因为过于偏执(之前写过有关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。例子很简单,关键是实现思路。如有不妥之处还请赐教。

转载于:https://my.oschina.net/u/3435444/blog/1507170

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值