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的个数.