C++入门(4)动态内存、命名空间、模板

C++ 程序中的内存分为两个部分:

栈:在函数内部声明的所有变量都将占用栈内存。
堆:这是程序中未使用的内存,在程序运行时可用于动态分配内存。

new和delete
new 运算符为任意的数据类型动态分配内存
delete 操作符释放它所占用的内存

double* pvalue = NULL; // 初始化为 null 的指针
pvalue = new double; // 为变量请求内存

一维数组
char* pvalue = NULL; // 初始化为 null 的指针
pvalue = new char[20]; // 为变量请求内存
delete [] pvalue; // 删除 pvalue 所指向的数组

二维数组

int **array
// 假定数组第一维长度为 m, 第二维长度为 n
// 动态分配空间
array = new int *[m];
for( int i=0; i<m; i++ )
{
    array[i] = new int [n]  ;
}
//释放
for( int i=0; i<m; i++ )
{
    delete [] arrary[i];
}
delete [] array;

对象同理
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // 删除数组

命名空间
作为附加信息来区分不同库中相同名称的函数、类、变量等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围。

#include <iostream>
using namespace std;
 
// 第一个命名空间
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
}
// 第二个命名空间
namespace second_space{
   void func(){
      cout << "Inside second_space" << endl;
   }
}
int main ()
{
 
   // 调用第一个命名空间中的函数
   first_space::func();
 
   // 调用第二个命名空间中的函数
   second_space::func();
 
   return 0;

嵌套的命名空间

namespace namespace_name1 {
   // 代码声明
   namespace namespace_name2 {
      // 代码声明
   }
}

using namespace namespace_name1::namespace_name2;

C++模板
模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码
函数模板
template ret-type func-name(parameter list)
{
// 函数的主体
}

类模板
template class class-name {
.
}

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
 
using namespace std;
 
template <class T>
class Stack {
  private:
    vector<T> elems;     // 元素
 
  public:
    void push(T const&);  // 入栈
    void pop();               // 出栈
    T top() const;            // 返回栈顶元素
    bool empty() const{       // 如果为空则返回真。
        return elems.empty();
    }
};
 
template <class T>
void Stack<T>::push (T const& elem)
{
    // 追加传入元素的副本
    elems.push_back(elem);   
}
 
template <class T>
void Stack<T>::pop ()
{
    if (elems.empty()) {
        throw out_of_range("Stack<>::pop(): empty stack");
    }
    // 删除最后一个元素
    elems.pop_back();        
}
 
template <class T>
T Stack<T>::top () const
{
    if (elems.empty()) {
        throw out_of_range("Stack<>::top(): empty stack");
    }
    // 返回最后一个元素的副本
    return elems.back();     
}
 
int main()
{
    try {
        Stack<int>         intStack;  // int 类型的栈
        Stack<string> stringStack;    // string 类型的栈
 
        // 操作 int 类型的栈
        intStack.push(7);
        cout << intStack.top() <<endl;
 
        // 操作 string 类型的栈
        stringStack.push("hello");
        cout << stringStack.top() << std::endl;
        stringStack.pop();
        stringStack.pop();
    }
    catch (exception const& ex) {
        cerr << "Exception: " << ex.what() <<endl;
        return -1;
    }
}
发布了21 篇原创文章 · 获赞 0 · 访问量 386

猜你喜欢

转载自blog.csdn.net/weixin_41605876/article/details/104748275
今日推荐