C++难点汇总

1、单重继承、多重继承格式及构造函数值传递

2、STL常用输入输出流及使用方法。

3、运算符重载。

4、C++模板编程。

1、单重继承、多重继承格式及构造函数值传递

一、单重继承
class 派生类名: public 基类名
{
  // 基类构造值传递格式1
  构造函数(基类参数1,基类参数2本类参数1,本类参数2,...):基类名( 基类参数1, 基类参数2 )
  {
      本类数据成员1 =  本类参数1;
      本类数据成员2=   本类参数2;
  }

 // 基类构造值传递格式2
构造函数(基参1,基参2本参1,本参2,...):基类名(基参1,基参2),本类数据成员1(本参1),本类数据成员2(本参2
{
}
  数据成员和成员函数声明及定义;
};

二、多重继承格式
class 派生类名: public 基类名1, public 基类名2,...
{
  构造函数(基类参数1,基类参数2,本类参数1,...):基类名1(基类参数1),基类名2(基类参数2)
  {
      本类数据成员1 =  本类参数1;
      .........
      .........
  }

 // 基类构造值传递格式2
  构造函数(基参1,基参2,本参1,本参2,...):
                  基类名1(基参1),
                  基类名2(基参2),
                  本类数据成员1(本参1),
                  本类数据成员2(本参2)

  {
  }
  数据成员和成员函数声明;
};

2、STL常用输入输出流及使用方法。

    文件输入输出流

        C++对文件的读写使用的是ifstream、ofstream和fstream流类,同样是依照“打开-->读写-->关闭”原语进行操作。文件读写所用到的很多常数都在基类ios中被定义出来。ifstream类只用于读取文件数据,ofstream类只用于写入数据到文件,fstream则可用于读取和写入文件的数据。

        ios::in        以读取方式打开文件
        ios::out      以写入方式打开文件
        ios::app      每次写入数据时,先将文件指针移到文件尾,以追加数据到尾部
        ios::ate      仅初始时将文件指针移到文件尾,仍可在任意位置写入数据
        ios::trunc   写入数据前,先删除文件原有内容(清空文件),当文件不存在时会创建文件
        ios::binary  以二进制方式打开文件,不作任何字符转换.

        std::cout << "this id is" << i << std::endl;
        std::cin >> i >> f;


3、运算符重载

        CMyTime& operator+(const CMyTime &obj) const;  //重载加法
                 { return *this }

        CMyTime& operator-(const CMyTime &obj) const;  //重载减法
                 { return *this }

        CMyTime& operator*(double n) const;                //重载乘法
                 { return *this }


4、函数模板(function template)和类模板(class template)

        // 函数模板
        template<typename T>
        bool equivalent( const T& a,  const  T&   b ) {
            return ! ( a < b )  &&  !( b  <  a );
        }

       // 类模板
        template<typename T=int> // 默认参数
        class bignumber {
            T    _v;
        public:
            bignumber( T   a ) :  _v( a ) {   }
            inline bool operator<(  const bignumber&   b  ) const;   // 等价于 (const bignumber<T>& b)

        };

        // 在类模板外实现成员函数
        template<typename T>
        bool bignumber<T>::operator<(const bignumber& b) const{
            return _v < b._v;
        }


        int main()
        {
            bignumber<> a(1), b(1); // 使用默认参数,"<>"不能省略
            std::cout << equivalent(a, b) << '\n'; // 函数模板参数自动推导
            std::cout << equivalent<double>(1, 2) << '\n';
            std::cin.get();    return 0;
        }

猜你喜欢

转载自blog.csdn.net/zhouqt/article/details/79349464