一、类和对象基本概念
1) 写出下面程序的运行结果:
#include <iostream.h>
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 <iostream.h>
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) 下面的程序输出结果是:
0
5
请填空补足程序。所填内容不允许包含分号。
class A {
public:
sizeof是什么 int val;
A(____________ ){ val = n; };
___A &________ GetObj() {
return _* this_______;
}
};
main() {
A a;
cout <<a.val << endl;
a.GetObj() = 5;
cout << a.val << endl;
}
/*
int n =0
A &
* this
*/
4) 下面程序的输出是:
3+4i
5+6i
请补足Complex类的成员函数。不能增加成员变量。
#include <iostream>
#include <string.h>
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 <iostream.h>
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 <iostream.h>
#include <string.h>
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) {
delete [] p;
p = new char[strlen(s)+1];
strcpy(p,s);
}
MyString( MyString & o ) {
p = new char[strlen(o.p ) + 1 ];
strcpy( p,o.p);
}
*/
7)下面程序的输出结果是:
5,5
5,5
请填空
#include <iostream.h>
#include <string.h>
class Base {
public:
int k;
Base(int n):k(n) { }
};
class Big
{
public:
int v;
Base b;
Big ________________ { }
Big ________________{ }
};
int main()
{
Big a1(5);
Big a2 = a1;
cout << a1.v << "," << a1.b.k << endl;
cout << a2.v << "," << a2.b.k << endl;
}
/*
Big(int n):v(n),b(n){ }
Big(Big & x):v(x.v),b(x.b.k){ }
*/
二、运算符重载
1)下面的MyInt类只有一个成员变量。MyInt类内部的部分代码被隐藏了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论