作业及其答案汇总图文稿
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
作业及其答案汇总
集团文件版本号:(M928-T898-M248-WU2669-I2896-DQ586-M1988)
一、类和对象基本概念
1) 写出下面程序的运行结果:
#include
class Apple {
private :
static int nTotalNumber;
public:
Apple()
{ nTotalNumber ++; }
~Apple( ) { nTotalNumber --; }
static void PrintTotal()
{ cout << nTotalNumber << endl; } };
int Apple::nTotalNumber = 0;
Apple Fun( const Apple & a )
{ a.PrintTotal(); return a ; }
int main () {
Apple * p = new Apple[4];
Fun( p[2]);
Apple p1, p2;
delete [] p;
p1.PrintTotal();
}
/*
4
1
*/
2) 写出下面程序的运行结果:
#include
class Sample{
public:
int v;
Sample() { };
Sample(int n):v(n) { };
Sample( Sample & x) { v = 2 + x.v ; } };
Sample PrintAndDouble( Sample o)
{
cout << o.v;
o.v = 2 * o.v;
return o;
}
int main()
{
Sample a(5);
Sample b = a;
Sample c = PrintAndDouble( b );
cout << endl;
cout << c.v << endl;
Sample d;
d = a;
cout << d.v ;
}
/*
9
22
5
*/
3) 下面的程序输出结果是:
5
请填空补足程序。所填内容不允许包含分号。class A {
public:
int val;
A(____________ ){ val = n; };
___A &________ GetObj() {
return _* this_______;
}
};
main() {
A a;
cout < a.GetObj() = 5; cout << a.val << endl; } /* int n =0 A & * this */ 4) 下面程序的输出是: 3+4i 5+6i 请补足Complex类的成员函数。不能增加成员变量。#include #include using namespace std; class Complex { private: double r,i; public: void Print() { cout << r << "+" << i << "i" << endl; } }; int main() { Complex a; a = "3+4i"; a.Print(); a = "5+6i"; a.Print(); } /* Complex() { }; Complex( char * s) { r = s[0] - '0'; i = s[2] - '0'; } */ 5) 下面程序的输出是: 10 请补足Sample类的成员函数。不能增加成员变量。#include class Sample{ public: int v; Sample(int n):v(n) { }; }; int main() { Sample a(5); Sample b = a; cout << b.v ; } /* Sample( Sample & x) { v = 2 * x.v ; } */ 6)下面程序的输出是: This Hello 请补足MyString类的成员函数。不能增加成员变量。 #include #include class MyString{ char * p; public: MyString( char * s ) { p = new char[strlen(s)+1]; strcpy(p,s); } ~MyString() { delete [] p;} const char * c_str() { return p;} }; int main() { MyString s1("This"), s2 =s1; s2.Copy ( "Hello"); cout << s1.c_str () << endl << s2.c_str () ; } /* void Copy( char * s) {