C++基础2020-11-10

2020-11-10  本文已影响0人  忻恆

C++ 拷贝构造函数

class Line
{
   public:
      int getLength( void );
      Line( int len );             // 简单的构造函数
      Line( const Line &obj);      // 拷贝构造函数
      ~Line();                     // 析构函数
 
   private:
      int *ptr;
};
// 成员函数定义,包括构造函数
Line::Line(int len)
{
    cout << "调用构造函数" << endl;
    // 为指针分配内存
    ptr = new int;
    *ptr = len;
}
 
Line::Line(const Line &obj)
{
    cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
    ptr = new int;
    *ptr = *obj.ptr; // 拷贝值
}
 
Line::~Line(void)
{
    cout << "释放内存" << endl;
    delete ptr;
}

C++ 友元函数

C++ 内联函数

C++ this 指针

C++ 指向类的指针

C++ 类的静态成员

静态成员函数

C++ 继承

多继承

class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};

重载运算符

class Line
{
   public:
      int getLength( void );
      Line( int len );             // 简单的构造函数
      Line( const Line &obj);      // 拷贝构造函数
      ~Line();                     // 析构函数
 
   private:
      int *ptr;
};
// 成员函数定义,包括构造函数
Line::Line(int len)
{
    cout << "调用构造函数" << endl;
    // 为指针分配内存
    ptr = new int;
    *ptr = len;
}
 
Line::Line(const Line &obj)
{
    cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
    ptr = new int;
    *ptr = *obj.ptr; // 拷贝值
}
 
Line::~Line(void)
{
    cout << "释放内存" << endl;
    delete ptr;
}

C++ 友元函数

C++ 内联函数

C++ this 指针

C++ 指向类的指针

C++ 类的静态成员

静态成员函数

C++ 继承

多继承

class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};

重载运算符

C++ 多态

class Shape {
      int area()
      {
         cout << "Parent class area :" <<endl;
      }
};
class Rectangle: public Shape{
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
      }
};
class Triangle: public Shape{
      int area ()
      { 
         cout << "Triangle class area :" <<endl;
      }
};

Shape *shape;
Rectangle rec(10,7);
Triangle  tri(10,5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的求面积函数 area
shape->area();

output:
Parent  class area 
Parent  class area

虚函数

C++ 数据抽象

两个重要的优势:

C++ 数据封装

C++ 接口(抽象类)

C++ 文件和流

从文件读取流和向文件写入流。这就需要用到 C++ 中另一个标准库 fstream,它定义了三个新的数据类型

在 C++ 中进行文件处理,必须在 C++ 源代码文件中包含头文件 <iostream> 和 <fstream>

打开文件

C++ 异常处理

上一篇 下一篇

猜你喜欢

热点阅读