C++是一门面向对象的语言,在C语言的基础上有了进一步的扩充与完善。
封装:封装是一个用来将对象的状态和行为捆绑到一个单一逻辑单元机制的正式术语。不是面向对象语言所特有,在面向过程的C语言中用结构封装了数据,函数封装了逻辑。但是面向对象封装了数据和逻辑,一定意义上面向对象的封装更加完美。
如果类中没有定义构造函数,编译器会提供一个默认构造函数,无返回值,无参数,函数体为空。但如果类中定义了构造函数,编译器就不再提供默认的构造函数。
如果类中没有定义析构函数,编译器会提供一个默认析构函数,但默认析构函数不会释放动态分配的资源。
~类名(){ }
#ifndef _ARRAY_H #define _ARRAY_H class Array { private: int *m_data;
int m_length; void SetLength(int l); void InitArray(); void SetValue(int index, int val); int GetLength(); int GetValue(int index); }; #endif
#include "Array.h"
#include <iostream>
#include <cstdlib>
using namespace std;
void Array::SetLength(int l)
{
m_length = l;
}
void Array::InitArray()
{
if (m_length < 0)
{
m_length = 0;
}
m_data = (int *)malloc(sizeof(int) * m_length);
if (NULL == m_data)
{
cout << "malloc failure!" << endl;
}
}
void Array::SetValue(int index, int val)
{
m_data[index] = val;
}
int Array::GetLength()
{
return m_length;
}
int Array::GetValue(int index)
{
return m_data[index];
}
#include "Array.h"
#include <iostream>
using namespace std;
int main()
{
int length, i;
Array a, b;
cout << "Please input " << endl;
cin >> length;
a.SetLength(length);
a.InitArray();
for (i = 0; i < a.GetLength(); i++)
{
a.SetValue(i, i + 1);
}
for (int j = 0; j < a.GetLength(); j++)
{
cout << a.GetValue(j) << endl;
}
return 0;
}