义务教育100条经典C++笔试题目.pptVIP

  • 15
  • 0
  • 约3.25万字
  • 约 120页
  • 2018-08-14 发布于江西
  • 举报
义务教育100条经典C++笔试题目.ppt

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 100条经典C++语言笔试题目 100、编写类 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 的上述 4 个函数。 100条经典C++语言笔试题目 【标准答案】 // String 的析构函数 String::~String(void) { delete [] m_data; // 由于 m_data 是内部数据类型,也可以写成 delete m_data; } 100条经典C++语言笔试题目 // String 的普通构造函数 String::String(const char *str) { if(str==NULL) { m_data = new char[1]; // 若能加 NULL 判断则更好 *m_data = ‘\0’; } else { int length = strlen(str); m_data = new char[length+1]; strcpy(m_data, str); } } 100条经典C++语言笔试题目 // 拷贝构造函数 String::String(const String other) { int length = strlen(other.m_data); m_data = new char[length+1]; // 若能加 NULL 判断则更好 strcpy(m_data, other.m_data); } 100条经典C++语言笔试题目 // 赋值函数 String String::operate =(const String other) { if(this == other) return *this; delete [] m_data; int length = strlen(other.m_data); m_data = new char[length+1]; strcpy(m_data, other.m_data); return *this; } * * * * * * * * * * * * * * * * * * * * * * * * * * 100条经典C++语言笔试题目 79、以下代码中的输出语句输出0吗,为什么? struct CLS { int m_i; CLS( int i ) : m_i(i) {} CLS() { CLS(0); } }; CLS obj; cout obj.m_i endl; 【标准答案】不能。在默认构造函数内部再调用带参的构造函数属用户行为而非编译器行为,亦即仅执行函数调用,而不会执行其后的初始化表达式。只有在生成对象时,初始化表达式才会随相应的构造函数一起调用。 100条经典C++语言笔试题目 80、How do you code an infinite loop in Cplus plus ? 【参考答案】while(1){} or for(;1;) 100条经典C++语言笔试题目 81、What are the values of a, b

文档评论(0)

1亿VIP精品文档

相关文档