C/C++日常学习总结(第十篇)string的实现&文件流操作

1.已知string原型,请编写下面的四个函数。

class String
{
public:
  String(const char* str=NULL);//普通构造函数
  String(const String &other);//拷贝构造函数
  ~String();//析构函数
  String &operate=(const String &other);//赋值函数
private:
   char* m_data;//用来保存字符串
  
};

【解析】:

String::String(const char *str)
{
  if ( str == NULL ) //strlen在参数为NULL时会抛异常才会有这步判断
  {
    m_data = new char[1] ;
    m_data[0] = '' ;
  }else
  {
    m_data = new char[strlen(str) + 1];
    strcpy(m_data,str);
  }
}
String::String(const String &other)
{
   m_data = new char[strlen(other.m_data) + 1];
   strcpy(m_data,other.m_data);
}
String & String::operator =(const String &other)
{
   if ( this == &other)
      return *this ;
   delete []m_data;
   m_data = new char[strlen(other.m_data) + 1];
   strcpy(m_data,other.m_data);
   return *this ;
}
String::~ String(void)
{
   delete []m_data ;
}



2.如何打印出当前文件的文件名,源文件的当前行号,执行函数的函数名?

cout<<__FILE__<<endl;
cout<<__LINE__<<endl;
cout<<__FUNCTION__<<endl;

【解析】:

__FILE__,__LINE__,__FUNCTION__这些都是系统定义的,是由编译器直接定义的,而不是在某个文件中定义的

 补充:打印类名    cout<<this->GetruntimeClass()->m_lpszClassName<<endl;

3.文件中有一组整数,要求排序后输出到另一个文件中

【解析】:

#include<iostream>

using namespace std;

#include<vector>

#include<fstream>



void order(vector<int> &data)

{

    int count = data.size() ;

    int tag = false ;

    for ( int i = 0 ; i < count ; i++)//冒泡排序

    {

         for ( int j = 0 ; j < count - i - 1 ; j++)

         {

           if ( data[j] > data[j+1])

           {

                tag = true ;

                int temp = data[j] ;

                data[j] = data[j+1] ;

                data[j+1] = temp ;

           }

         }

         if ( !tag )

           break ;
    }
}

void main()

{

   std::vector<int> data;

   ifstream in("C:\\data.text");

   if(!in)

   {

        cout<<"error"<<endl;

        exit(1);

   }

   int temp;

   while(!in.eof())

  {

     in>>temp;

    data.push_back(temp);

  }

  in.close();

  order(data);

  ofstream out("C:\\result.text");

  if(!out)

  {

       cout<<"error"<<endl;

       exit(1);

  }

  for(int i=0;i<data.size();++i)

  {

      out<<data[i]<<" ";

  }

   out.close();

}

 

 

4.求下面函数的返回值,假设x=9999.

int funx(int x)
{ 
    int ncountx=0;
    while(x)
     {
         ncountx++;
         x=x&(x-1);
     }
     return ncountx;
}

【解析】:

 答案为:8,思路把x转换成2进制,查看1的个数.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值