C++练习

选择填空

  1. 在每个C++程序中都必须包含一个函数,这个函数的名字为( )。
  2. x和y都是bool型变量,表达式x&&y为true的条件是()。

  3. 下面哪一个关键字不能作为函数的返回类型?A.void B.int C.new D.long
  4. a是一个整型数组的名字,则元素a[4]的地址为()。A.a+4 B.a+8 C.a+16 D.a+32
  5. 假定AB是一个类,执行语句AB a(4), b[3], *p[2];调用AB类的构造函数的次数为()。
  6. 在32位计算机上,int型的变量在内存中一般占()个字节。
  7. 若定义int m = 5, y = 2;,则表达式y+=y-=m*=y后的值是()。
  8. x>=3||x<-5的非,不用操作符!实现,可以表示为()。

  9. 执行int m = 5; do{ cout << '*'; m--; }while(m+3>0);将输出()个*号。

  10. 已知数组a定义为int a[][5]={ {1},{2},{3} };则数组a共有()元素。
  11. 已知数组a定义为int a[5] ={78,80,93,100,65};,并且已知sizeof(int)的值是4,设数组a的首地址是2000H,那么第三个元素93的地址为()。
  12. 已知数组a定义为char a[]="good morning";,请写出strstr(a,"mo")的值为()。
  13. C++语言起源于()语言,并在其基础上增加了面向对象的特性。
  14. 定义常值变量的修饰符是()
  15. for(int i = 0, j = 10; i = j = 10; i++, j++)这个循环的循环次数是()次

  16. 已知数组a的定义为int a[5]={10,20,30};,当有sizeof(int)值为4时,数组a占用了()字节。
  17. 已知一个函数的定义是:double Area(double r) { return 3.14*r*r; },则该函数的原型是()。
  18. 访问指针变量所指向的数据应该用操作符()。
  19. 一个联合对象所占用的存储空间的大小为()。
  20. 当对象调用成员函数时,除了将实参传递给成员函数中显式说明的形参外,还同时把对象的地址传送给成员函数中默认的指针参数()中。
  21. 要使用setw流控制符,需要包含的头文件是()。
  22. 下列符号中,可以作为C++标识符的是():A.6str B.sp_str C.who? D.switch
  23. 有定义int p, q;下列语句不正确的是:A. p*=3; B. p/=q; C.p+=3; D. p&&=q;

找出以下程序中的语法错误,并作出解释。

  1.    1 #include <stdlib.h>
       2 int main() {
       3     const int size;
       4     size = 10;
       5     int a[size];
       6     int *p1 = new int[size];
       7     int *p2 = malloc(sizeof(int)* size);
       8     int *p3 = new int(size);
       9     for(int i = 0; i < size; i++) {
      10         a[i] = i;
      11         p1[i] = a[i] * i;
      12         p2[i] = p1[i] * i;
      13         p3[i] = p2[i] * i;
      14     }
      15     int sum;
      16     for(int i = 0; i < size; i++)
      17         sum += a[i] + p1[i] + p2[i] + p3[i];
      18     cout << sum;
      19     delete p1;
      20     delete [] p2;
      21     delete p3;
      22 }
    
  2.    1 #include <iostream>
       2 using namespace std;
       3 class N {
       4     static int n = 0;
       5     int i;
       6 public:
       7     void N() : i(0) { }
       8     void N(int a = 0) : i (a) { }
       9     void N(int a = 0, int b) : i(a), n(b) { }
      10     int get() const { return i++; }
      11     void set(int a) { i = a;}
      12     void print() const { cout << get() << endl;}
      13     static int getn() const { return n; }
      14     static void setn(int a) { n = a; i++; }  
      15 }
      16 int main() {
      17     cout << N::n << endl;
      18     cout << N::getn() << endl;
      19     cout << get() << endl;
      20     cout << N::get() << endl;
      21     cout << N::setn(10) << endl;
      22     N *p = new N(5);
      23     N n();
      24     n.set(10);
      25     n.setn(11);
      26     p.set(5);
      27     delete p;
      28 }
    
  3.    1 #include <string>
       2 #include <iostream>
       3 using namespace std;
       4 class S {
       5 public:
       6     S(int a0) { cout << a0 << endl; }
       7     S(double a0, int b0) : d(a0), b(b0){ cout << a0 << b0 << endl; }
       8     S(char *p0) : d(a), b(2) { cout << p << endl;} 
       9     S(int &a0) : a(0), b(1), c("abc"), d(a0), p(new int) { }
      10 private:
      11     int a;
      12     const int b;
      13     string c;
      14     int &d;
      15     int *p;
      16 };
      17 int main() {
      18     S a(1);
      19     S b;
      20     S c(0.0, 1);
      21     S d("hello");
      22     S e(true);
      23     S f(a);
      24     e = a;
      25 }
    
  4.    1 #include <string>
       2 #include <iostream>
       3 using namespace std;
       4 class Person{
       5 public:
       6     Person(string name) : name_ (name) { }
       7     virtual void print() const = 0 { cout << name_; }
       8     virtual bool compare(Person p) const { return p.name_ == name_; }
       9 protected:
      10     string name_;
      11 };
      12 class Student : public Person {
      13     Student(string name, string id) { name_ = name; id_ = id; }
      14     Student(Person p, string id) { name_ = p.name_; id_ = id;}
      15     bool compare(Student s) const { return s.name_==name_ && s.id_ == id_; }
      16     void print() { cout << name_ << id_ << endl; }
      17 private:
      18     string id_;
      19 };
      20 
      21 int main() {
      22     Person p("Mike");
      23     Student s("jack", "12345");
      24     Student t(p, "23424");
      25     cout << s.compare(t);
      26     cout << p.compare(t);
      27     cout << s.compare(p);
      28     s.print();
      29     s.Person::print();
      30 }
    
  5.    1 class Integer{
       2 public:
       3     Integer(int a = 0) : i(a) {}
       4     Integer operator+(int a, int b) { return a + b;}
       5     Integer operator-() { return -i; }
       6     Integer operator+() { return i; }
       7     Integer operator++() { return ++i; }
       8     Integer operator++(int) { return i++; }
       9     bool operator<>(int a) { return i != a; }
      10 private:
      11     int i;
      12 };
      13 void operator>>(ostream &os, Integer i) {
      14     os << i;
      15 }
      16 istream & operator<<(istream &is, Integer i) {
      17     is >> i.i;
      18     return is;
      19 } 
      20 Integer operator-(Integer a, Integer b) {
      21     return a.i - b.i;
      22 }
      23 int main() {
      24     Integer i(-1);
      25     Integer j;
      26     cin >> j;
      27     i = -i;
      28     i = i - j;
      29     i = i + 10;
      30     cout << i;
      31 }
    

读程序,写出程序运行的结果

  1.    1 #include <iostream>
       2 using namespace std;
       3 int inc( int &a) {
       4     return ++a;
       5 }
       6 int dec( int a) {
       7     return --a;
       8 }
       9 int main() {
      10     int b = 10;
      11     cout << inc(b) << endl;
      12     cout << dec(b) << endl;
      13     cout << inc(b) << endl;
      14 }
    
  2.    1 #include <iostream>
       2 #include <string>
       3 using namespace std;
       4 int f( string a );
       5 int f( int b , int c = 1);
       6 int f( bool b);
       7 int main() {
       8     string s = "";
       9     cout << f(s) << endl;
      10     cout << f('\060') << endl;
      11     cout << f(1, 2) << endl;
      12     cout << f(false) << endl;
      13     cout << f(0) << endl;
      14 }
      15 int f( string a) {
      16     return a.length();
      17 }
      18 int f( int b, int c) {
      19     return b * c + b + c + 1;
      20 }
      21 int f(bool b) {
      22     return b?1:-1;
      23 }
    
  3.    1 #include <iostream>
       2 using namespace std;
       3 class Z {
       4 public:
       5     Z(int i) : id(i) { cout << id << " created" << endl; }
       6     ~Z() { cout << id << " destroyed" << endl; }
       7     Z(Z &z) : id(z.id) { cout << id << " created a copy" << endl; }
       8 private:
       9     int id;
      10 };
      11 Z z(0);
      12 int main() {
      13     cout << "main start" << endl;
      14     Z z1(1);
      15     Z z2(2);
      16     Z *z3 = new Z(3);
      17     Z z4(z1); 
      18 }
    
  4.    1 #include <iostream>
       2 using namespace std;
       3 class X {
       4 public: 
       5     X(int a) : x(a) { cout << "create X:" << x << endl; }
       6     ~X() { cout << "destroy X:"<< x << endl; }
       7 private:
       8     int x;
       9 };
      10 class Y : public X{
      11 public:
      12     Y() : x(1), X(2) { cout << "create Y" << endl; }
      13     ~Y() { cout << "destroy Y" << endl; }
      14 private:
      15     X x;
      16 };
      17 
      18 int main() {
      19     X x(5);
      20     Y  y;
      21 }
    
  5.    1 #include <iostream>
       2 using namespace std;
       3 class B{
       4 public:
       5     virtual void f() { cout << "B::f() "; }
       6     void g() { cout << "B::g() "; }
       7     virtual void h() { f(); }    
       8 };
       9 class D : public B {
      10 public:
      11     void f() { cout << "D::f() "; }
      12     void g() { cout << "D::g() "; }
      13 };
      14 int main() {
      15     B b;
      16     b.f(); b.g(); b.h();
      17     cout << endl;
      18     B *p = &b;
      19     p->f(); p->g(); p->h();
      20     cout << endl;
      21     p = new D;
      22     p->f(); p->g(); p->h();
      23     cout << endl;
      24     B &r = *p;
      25     r.f(); r.g(); r.h();
      26     cout << endl;
      27     delete p;
      28 }
    
  6.    1 #include <iostream>
       2 using namespace std;
       3 class B{
       4 public:
       5     B () { cout << "create B" << endl; }
       6     virtual ~B() { cout << "destroy B" << endl; }
       7     virtual void f() { cout << "B::f()" << endl; }
       8     virtual void f(int a) { cout << "B::f(int)" << endl; }
       9 };
      10 class D : public B {
      11 public:
      12     D() { cout << "create D" << endl; }
      13     virtual ~D() { cout << "destroy  D" << endl; }
      14     virtual void f() { cout << "D::f()" << endl; }
      15     virtual void f(bool a) { cout << "D::f(bool)" << endl; }
      16 };
      17 int main() {
      18     B *p = new B;
      19     p->f();
      20     p->f(0);
      21     delete p;
      22     p = new D;
      23     p->f();
      24     p->f(0);
      25     delete p;
      26     D *d = new D;
      27     d->f();
      28     d->f(0);
      29     delete d;
      30 }
    
  7.    1 #include <iostream>
       2 using namespace std;
       3 class D {
       4 public:
       5     D() { cout << "D created" << endl; }
       6     D(D&) { cout << "D created a copy" << endl; }
       7     ~D() { cout << "D destroyed" << endl; }
       8     D& operator=(D&) { cout << "D assigned" << endl; return *this; }
       9     void operator++() { cout << "operator++" << endl; }
      10     void operator++(int) { cout << "operator++ with int" << endl; }
      11 };
      12 int main() {
      13     D d1;
      14     D d2(d1);
      15     d1 = d2;
      16     ++d1;
      17     d2++;
      18 }
    

程序填空题

  1. 输入一组数,求它们的总和。以EOF标志输入的结束。

    #include <iostream>
    using namespace std;
    int main(){
        int i, sum = 0;
        while(①____________)
            sum += i;
        cout << sum;
    }
  2. 按照右对齐输出一组数

    #include <iostream>
    #include <iomanip>
    using namespace std;
    int main() {
        int n;
        cin >> n;
        for(int i = 0;i < n; i++) {
            for(int j = 0; j <= i; j++)
                ②_____________________
            cout << endl;
        }      
    }

    输入5,输出:

       1
       2   4
       3   6   9
       4   8  12  16
       5  10  15  20  25
  3. 交换两个参数的函数

    void swap(③_______________) {
        int temp = a;
        a = b;
        b = temp;
    }
  4. 打印时间的函数

    #include <iostream>
    using namespace std;
    void print_clock(④__________________________) {
        cout << hour << ":" << minute << ":" << second;
    }
    int main(){
        print_clock(10, 20, 30); // output: 10:20:30
        print_clock(10, 20);     // output: 10:20:0
        print_clock(10);         // output: 10:0:0
        print_clock();           // output: 0:0:0
    }
  5. 打印参数的类型

    #include <iostream>
    using namespace std;
    void print_type(⑤___________) {
        cout << "int type" << endl;
    }
    void print_type(⑥___________) {
        cout << "char type" << endl;
    }
    
    int main() {
        print_type(20);  // output: int type
        print_type("hello world"); //output: char type
    }
  6. 日期对象的创建

    class Date{
        int year, month, day;
    public:
        ⑦__________________________________
        {
        }
        void display() {
            cout << year <<"-" << month <<"-"<<day;
        }
    };
    int main(){
        Date d(1988, 10, 12);
        d.display(); //output: 1988-10-12
    }
  7. 任务计数

    class Task{
    public:
        static int count;
        Task() {count++;}
        ~Task() {count--;}
    };
    ⑧_____________________
    int main() {
        cout << Task::count; //output: 0
        Task *t = new Task;
        cout << t->count;    //output: 1
        delete t;
        cout << Task::count; //output: 0
    }
  8. 数组

    class Array{
        int *data;
    public: 
        Array(int n) {
            data = new int[n];
        }
        ⑨_____________________
        {
            delete [] data; //free memory when object destroyed
        }
    };
  9. 字符串求较大者

    #include <string>
    using namespace std;
    int main() {
        ⑩______________
        cin >> str1 >> str2;
        cout << "The bigger string is "<< (str1>str2?str1:str2);    
    }
  10. cin和cout

    #include <iostream>
    ⑪___________________ {
        int cin = 0; 
        int &cout = cin;
    }
    int main() {
        std::cin >> czk::cin;
        std::cout<< czk::cout;
    }

编程题,按要求编写程序

  1. 实现字符串类string,声明如下

       1 class string {
       2 public:
       3         string(const char *str = "");           // 普通构造函数
       4         string(const string &other);            // 拷贝构造函数
       5         ~string();                                          // 析构函数
       6         string & operator = (const string &other);      // 赋值函数
       7     bool operator==(const string &s);
       8     bool operator!=(const string &s);
       9     bool operator<(const string &s);
      10     bool operator>(const string &s);
      11     bool operator<=(const string &s);
      12     bool operator>=(const string &s);
      13     string operator +(const string &s); //连接
      14     string operator +=(const string &s);
      15     int length() const;
      16     bool empty() const;
      17         char* c_str()   { return m_data; }
      18 private:
      19         char *m_data;                               // 用于保存字符串
      20 };
      21 ostream &operator<<(ostream &os, const string &s);
      22 istream &operator>>(istream &is, string &s);
    
  2. 实现完整的复数运算,复数类的声明如下:

       1 class complex {
       2 public:
       3     complex(double r = 0.0, double i= 0.0);
       4     complex operator+();
       5     complex operator-();
       6     complex operator+=(complex);
       7     complex operator-=(complex);
       8     complex operator*=(complex);
       9     bool operator!(); //非0返回假,0返回真
      10     double abs(); //取模
      11     double arg(); //取角度
      12     complex conj(); //共轭
      13     double &real(); //实部
      14     double &imag(); //虚部
      15 private:
      16     double real_, imag_;
      17 };
      18 ostream &operator<<(ostream &os, complex);
      19 istream &operator>>(istream &is, complex &);
      20 complex operator+(complex a, complex b);
      21 complex operator*(complex a, complex b);
      22 complex operator-(complex a, complex b);
      23 complex operator==(complex a, complex b);
      24 complex operator!=(complex a, complex b);
    
  3. 实现Stack类,提供push(把一个元素放入栈中),pop(把栈中最后一个元素删去),top(取栈中最后一个元素)。请实现Stack类,使其能够得到正确的运行结果。

       1 #include <iostream>
       2 using namespace std;
       3 int main() {
       4     Stack s1(5);
       5     for(int i = 0; i < 3; i++) s1.push(i);
       6     Stack s2(s1);
       7     while(s1.size() > 0) {
       8         cout << s1.top() << endl;
       9         s1.pop();
      10     }
      11     s1 = s2;
      12     for(int i = 3; i < 5; i++) s1.push(i);
      13     while(s1.size() > 0) {
      14         cout << s1.top() << endl;
      15         s1.pop();
      16     }
      17 }
    
  4. 实现队列Queue类,提供enqueue(把一个元素放在队列的末尾中),dequeue(把队列中第一个元素删去),front(取队列中第一个元素的值),back(取队列最后一个元素的值)。请实现Queue类,使其能够得到正确的运行结果。

       1 #include <iostream>
       2 using namespace std;
       3 int main() {
       4     Queue s1(5);
       5     for(int i = 0; i < 3; i++) s1.enqueue(i);
       6     Queue s2(s1);
       7     while(s1.size() > 0) {
       8         cout << s1.front() << endl;
       9         s1.dequeue();
      10     }
      11     s1 = s2;
      12     for(int i = 3; i < 5; i++) s1.enqueue(i);
      13     while(s1.size() > 0) {
      14         cout << s1.front() << endl;
      15         s1.dequeue();
      16     }
      17 }
    
  5. 财务软件。Account为账户,AccountList为账户的集合,两个类的声明如下,请给出这两个类的实现。

       1 class Account {
       2 public:
       3     Account(string name, int type, double amount);
       4     string &name();
       5     int &type();
       6     double &amount();
       7 private:
       8     string name_;
       9     int type_;
      10     double amount_;
      11 };
      12 class AccountList {
      13 public:
      14     AccountList(int capacity);
      15     void AddAccount(Account account);
      16     void RemoveAccount(string name);
      17     int Find(string name);
      18     Account &At(int i);
      19 private:
      20     int capacity_;
      21     int size_;
      22     Account *accounts;
      23 };
    
  6. 学校的人事关系。学校里面有四类人:人(Person),学生(Student),教师(Teacher),助教(Assistant)。其中助教是一类特殊的人,他们是教师,同时也是学生。请完成以下程序,使之能得到正确运行结果。

       1 #include <iostream>
       2 #include <string>
       3 using namespace std;
       4 int main() {
       5     Person *p[4];
       6     p[0] = new Person("jack");
       7     p[1] = new Student("rose", "12345");
       8     p[2] = new Teacher("czk", "lecturer");
       9     p[3] = new Assistant("oldbig", "23456", "assistant");
      10     for(int i= 0; i < 4; i++) {
      11         p[i] -> print();
      12         cout << endl;
      13     }
      14 }
    
  7. 声明一个Shape抽象类,在此基础上派生出Rectangle类(矩形)和Circle类(圆),二者都有GetArea()函数计算对象的面积,请按下面的要求给出Shape类、Rectangle类、Circle类的实现:Rectangle类有Width宽度,Height高度属性;Circle类有Radius半径属性;Rectangle类和Circle类的构造函数用以初始化上述参数;每个类都有GetArea函数,用以计算此形状的面积;主函数(如下)已经写好,对Rectangle、Circle类进行测试,使它们以统一的操作界面输出面积。

       1 #include <iostream>
       2 using  namespace  std;
       3 int main()
       4 {
       5         Shape *shapes[5];
       6         shape[0] =  new Rectangle(1.0, 2.0);
       7         shape[1] =  new Circle(5.0);
       8         shape[2] =  new Circle(1.0);
       9         shape[3] =  new Rectange(3.0, 1.5);
      10         shape[4] =  new Circle(0.0);
      11         for( int i = 0; i < 5; i++)
      12                 cout<<"Area of shape "<<i <<" is "<<shape[i]->GetArea()<<endl;
      13 }
    
  8. 设计一个分数类Fraction,表示分数,可以进行算术运算,并完成输入输出,输出时分子分母能够约到最简。请完成Fraction这个类,并可以使如下程序正常运行:

    int main() {
        Fraction f1(1, 8);
        Fraction f2(1, 4);
        cout << f1+f2 << endl;
        cout << f1-f2 << endl;
        cout << f1*f2 << endl;
        cout << f1/f2 << endl;
        cout << -f1 << endl;
        cout << (-4 %2==0) << endl;
        if(f1==f2)
            cout << "f1 and f2 are same "<<endl;
        else if(f1 > f2)
            cout << "f1 is bigger" << endl;
        else
            cout << "f2 is bigger" << endl;
    }

    参考程序:

       1 #include <iostream>
       2 using namespace std;
       3 
       4 class Fraction {
       5     int num, denom;
       6 public:
       7     void normalize() {
       8         if(denom < 0) {
       9             denom = -denom;
      10             num = -num;
      11         }
      12         if(denom == 0)
      13             num = 0;
      14         else if(num == 0)
      15             denom = 1;
      16         else {
      17             for(int i = 2; i <= min(abs(num), denom);)
      18                 if(num%i==0 && denom%i==0) {
      19                     num /= i;
      20                     denom /= i;
      21                 } else {
      22                     i++;
      23                 }
      24         }
      25     }
      26     Fraction(int n, int d):num(n), denom(d){
      27         normalize();
      28     }
      29     Fraction(const Fraction &f):num(f.num), denom(f.denom){
      30         normalize();
      31     }
      32     Fraction operator+(Fraction a) {
      33         return Fraction(num*a.denom+denom*a.num, denom*a.denom);
      34     }
      35     Fraction operator-(Fraction a) {
      36         return Fraction(num*a.denom-denom*a.num, denom*a.denom);
      37     }
      38     Fraction operator*(Fraction a) {
      39         return Fraction(num*a.num, denom*a.denom);
      40     }
      41     Fraction operator/(Fraction a) {
      42         return Fraction(num*a.denom, denom*a.num);
      43     }
      44     Fraction operator-() {
      45         return Fraction(-num, denom);
      46     }
      47     bool operator==(Fraction f){
      48         return (*this-f).num == 0;
      49     }
      50     bool operator>(Fraction f){
      51         return (*this-f).num > 0;
      52     }
      53     bool operator<(Fraction f){
      54         return (*this-f).num < 0;
      55     }    
      56     friend ostream& operator<<(ostream &os, const Fraction &f) {
      57         return cout << f.num << "/" << f.denom;
      58     }
      59 };
      60 
      61 int main() {
      62     Fraction f1(1, 8);
      63     Fraction f2(1, 4);
      64     cout << f1+f2 << endl;
      65     cout << f1-f2 << endl;
      66     cout << f1*f2 << endl;
      67     cout << f1/f2 << endl;
      68     cout << -f1 << endl;
      69     cout << (-4 %2==0) << endl;
      70     if(f1==f2)
      71         cout << "f1 and f2 are same "<<endl;
      72     else if(f1 > f2)
      73         cout << "f1 is bigger" << endl;
      74     else
      75         cout << "f2 is bigger" << endl;
      76 }
    

The end

C++练习 (2008-06-27 10:53:51由218编辑)