现在的位置: 首页 > 综合 > 正文

C++相关的基础题

2013年12月08日 ⁄ 综合 ⁄ 共 1890字 ⁄ 字号 评论关闭

 

#ifndef __INCvxWorksh
#define __INCvxWorksh
#ifdef __cplusplus

extern "C" {
#endif
/*...*/
#ifdef __cplusplus
}

#endif
#endif /* __INCvxWorksh */
  解答:

  头文件中的编译宏

#ifndef __INCvxWorksh
#define
 __INCvxWorksh
#endif
  的作用是防止被重复引用。

  作为一种面向对象的语言,C++支持函数重载,而过程式语言C则不支持。函数被C++编译后在symbol库中的名字与C语言的不同。例如,假设某个函数的原型为:

void foo(int x, int y);
  该函数被C编译器编译后在symbol库中的名字为_foo,而C++编译器则会产生像_foo_int_int之类的名字。_foo_int_int这样的名字包含了函数名和函数参数数量及类型信息,C++就是考这种机制来实现函数重载的。

  为了实现CC++的混合编程,C++提供了C连接交换指定符号extern "C"来解决名字匹配问题,函数声明前加上extern "C"后,则编译器就会按照C语言的方式将该函数编译为_foo,这样C语言中就可以调用C++的函数了。

编写类String的构造函数、析构函数和赋值函数,已知类String的原型为:

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

//普通构造函数

String::String(const char *str)
{
 if(str==NULL)
 {
  m_data = new char[1]; // 得分点:对空字符串自动申请存放结束标志'/0'的空
  //加分点:对m_dataNULL 判断
  *m_data = '/0';
 }
 else
 {
  int length = strlen(str);
  m_data = new char[length+1]; // 若能加 NULL 判断则更好
  strcpy(m_data, str);
 }
}

// String的析构函数

String::~String(void)
{
 delete [] m_data; // delete m_data;
}

//拷贝构造函数

String::String(const String &other)    // 得分点:输入参数为const
{
 int length = strlen(other.m_data);
 m_data = new char[length+1];     //加分点:对m_dataNULL 判断
 strcpy(m_data, other.m_data);
}

//赋值函数

String & String::operate =(const String &other) // 得分点:输入参数为const
{
 if(this == &other)   //得分点:检查自赋值
  return *this;
 delete [] m_data;     //得分点:释放原有的内存资源
 int length = strlen( other.m_data );
 m_data = new char[length+1];  //加分点:对m_dataNULL 判断
 strcpy( m_data, other.m_data );
 return *this;         //得分点:返回本对象的引用
}

编写一个函数,得到char p[100]大小空间。

 

基础是根本,连根基不好,楼越高则越危险!

 

void GetMemory( char **p, int num )
{
 *p = (char *) malloc( num );

if ( *p == NULL )
{
 ...//进行申请内存失败处理
}

void Test( void )
{

 char *str = NULL;
 GetMemory( &str, 100 );
 strcpy( str, "hello" );
 printf( str ); free(str);
}

 牢记“[]  ->  .”的优先级高于 *(解地址)
++ -- *(解地址) &(取地址)的结合性是“自右向左”
float (*h)();
表示h是一个指向返回值为浮点类型的函数的指针,因此,
(float (*)())
表示一个“指向返回值为浮点类型的函数指针”的类型转换符。

抱歉!评论已关闭.