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; }