2022c++(Ⅱ)

选择

  1. I in C++ , There is a kind of class that it can only be inherited but cannot be initiated, we call that class as a ( ),to define that kind of class, it has to have at least a ( ) 。(A) virtual function (B) pure virtual function (C) abstract class (D)friend class

根据题意,应选b:纯虚函数及c:抽象类。

一个包含纯虚函数的类无法创建对象,相应的将一个抽象类作为一个数据成员的类也无法创建对象。

  1. Assume that AB is a class, the declaration of copy constructor of that class should be ( )。(A)AB&(AB x) (B)AB(AB x) (C)AB(AB &x) (D)AB(AB *x)

根据题意,应为c

用该类的对象创建另一个对象,即复制,需要传引用,防止在生成一堆数据浪费数据

  1. For the member of a structure, the default access modifier is ( )。

    (A) public; (B) private; (C) protected; (D) static;

    根据题意,应为a

    类的默认属性使私有,而结构体默认属性是公有

  2. Assume AB is a class, to execute statement “AB a(4),b[3],*p[2];”, how many times to invoke the constructor?( )。

    (A)3 (B) 4 (C) 6 (D) 9

    操作以左往右分别为,初始化的带参构造,默认构造的对象数组,未分配空间的指针数组

  3. Which of the following is not correct ( )

    1. The name of constructor is same as the name of the class

    2. class constructor could have default parameters

    3. the default return type of a constructor is of type int

    4. the constructor can be overloaded

    构造函数不能return,也吗,没有指明返回类型

  4. Parameterized stream manipulator setfill specifies the fill character that is displayed when an output is displayed in a field wider than the number of characters or digits in the output. The effect of setfill applies:

    1. Only to the current value being displayed.
    2. Only to outputs displayed in the current statement.
    3. Until explicitly set to a different setting.
    4. Until the output buffer is flushed.

std::setfill 是一个操纵符,它用于设置输出流的填充字符。当你需要在输出中对齐数据时,setfill 可以帮助你指定一个字符,当使用 setw 函数来设定输出宽度时,这个字符会被用来填充不足的部分。若字符超出了,则不会截断。

  1. Assuming the following is the beginning of the constructor definition for class Circle which inherits from class Point,Circle::Circle( double r, int a, int b ) : Point( a, b ) The second line:

    1. Invokes the Point constructor with values a and b.
    2. Causes a compiler error.
    3. Is unnecessary because the Point constructor is called automatically.
    4. Indicates inheritance.

    用于给point中的可能私有数据成员赋值等操作,总之可用,不会报错

  2. Which of the following assignments would be a compilation error?

    1) Assigning the address of a base-class object to a base-class pointer.
    2) Assigning the address of a base-class object to a derived-class pointer.
    3) Assigning the address of a derived-class object to a base-class pointer.
    4) Assigning the address of a derived-class object to a derived-class pointer.

    比如你能说狗是动物,但不能说动物是狗

  3. Assume class T is declared as following,which of the following declaration of the function fF() is not correct( )。

class T

{ int i;

friend void fF(T&,int) ;

};

1) void fF (T &objT,int k) { objT.i = k+1; }

2) void fF (T &objT,int k) { k = objT.i+1; }

3) void T::fF (T &objT,int k) { k += objT.i; }

4) void fF (T &objT,int k) { objT.i += k; }

显而易见

纠错

Find out errors in the following code, and correct them.

  1. Following is the destructor function prototype in Time class definition:

    void ~Time( int );

~Time( );

  1. Following is part of the Time class definition:
class Time { 

public:
private:

int hour = 0;
int minute = 0;
int second = 0;

}; // end class Time

没眼看

模拟

Write the output of the following program.

#include<iostream> 
using namespace std;
class test{
private:

int num;
float fl;
public:
test();
int getint(){ return num;}
float getfloat(){ return fl;}
~test();
};

test::test()
{

cout<<"Initailizing default"<<endl;
num = 0; fl = 0.0;

}

test::~test(){

cout<<"Destructor is active" <<endl;

}

int main()
{
test array[2];
cout<<array[1].getint()<< " " <<array[1].getfloat()<<endl;

}
Initailizing default
Initailizing default
0 0
Destructor is active
Destructor is active

此处float输出为0.

2.

#include <iostream> 
using namespace std;
class A
{
public:

A()
{ cout <<" A::A() called.\n";}
virtual ~A()
{ cout<<"A::~A() called.\n";}

};
class B: public A
{
public:

B(int i)
{
cout\<\<"B::B()called.\n";
buf = new char\[i\];
}

virtual ~B()
{ delete [] buf;
cout\<\< "B::~B() called.\n";
}

private:

char * buf;

};
void fun(A * a) {
delete a;

}
void main() {

A * a = new B(15);
fun(a);

}
A::A() called.
B::B()called.
B::~B() called.
A::~A() called.

继承实际是在子类内部开了一个属于父类的空间。

无论继承还是声明为类的数据成员,都是先于该类被创建的,当然也会最后被析构。

3.

#include<iostream> 
using namespace std;
class T
{
public:

T(int x)
{ a=x; b*=x;};

static void display(T c)
{ cout<<"a="<<c.a<<'\t'<<"b="<<c.b<<endl; }
private:

int a;
static int b;

} ;
int T::b=4;
int main()
{

T A(3),B(2);

T::display(A);

T::display(B);

}
a=3 b=24
a=2 b=24

因为输出是后面的事,此时赋值全部完成了

4.

#include <iostream> 
using namespace std;
class B
{
int b;
public: B(int i) { b=i; }
virtual void virfun()
{ cout<< "B::b: "<<b<<endl;
}

};
class D: public B
{ int d;
public:

D(int i,int j): B(i) { d=j; }

void virfun() { B::virfun(); cout<<"D::d: "<<d<<endl; }

};

void fun(B *objp) { objp->virfun(); }
void main() { B *pd ;
pd=new B(3) ;
fun(pd);
pd=new D(5,7);
fun(pd);

}
B::b: 3
B::b: 5
D::d: 7

5.

#include <iostream>

#include <string>
#include <iomanip>
using namespace std;
class Employee
{
public:

Employee(const long k ,const char* str )
{
number = k;
strcpy_s(name,20,str);
}
virtual ~Employee()
{
name[0] = '\0';
}
const char * getName() const{ return name;}
const long getNumber() const { return number;}
virtual double earnings() const=0;
virtual void print() const
{ cout <<number<<setw(16)<<name ;}

Employee * next;

protected:

long number; char name[20];

};


class Manager : public Employee
{
public:

Manager(const long k , const char str, double salary): Employee(k,str)

{
setMonthlySalary(salary);
}

~Manager() { }
void setMonthlySalary(double salary) { monthlySalary = salary;}
virtual double earnings() const { return monthlySalary;}
virtual void print() const { Employee::print(); cout<<setw(16)\<\<"Manager\n";}

private:

double monthlySalary ;

};

class HourlyWorker : public Employee
{
public:

HourlyWorker(const long k , const char * str, double w=0.0, int h=0 ): Employee(k,str){ setWage(w); setHours(h);}
~HourlyWorker(){}
void setWage(double w) { wage = w ;}
void setHours(int h) { hours = h ;}
virtual double earnings() const { return wage * hours ;}
virtual void print() const
{
Employee::print(); cout<<setw(16)<<"Hours Worker\n"<< "\t\twageperhour "<<wage\<<" Hours"<<hours;
cout\<\<" earned \$"\<\<earnings()\<\<endl;
}
private:

double wage;
double hours;
};


class PieceWorker : public Employee
{
public:

PieceWorker(const long k , const char * str, double wage =0.0, int quantity=0 ):Employee(k,str)
{ setWage(wage); setQuantity(quantity);}

~PieceWorker() { }
void setWage ( double wage ){ wagePerPiece = wage ;}
void setQuantity ( int q){ quantity = q ;}
virtual double earnings() const { return wagePerPiece * quantity; }
virtual void print() const
{
Employee::print(); cout\<\<setw(16) \<\< "Piece Worker\n" ;
cout\<\<"\t\twagePerPiece "\<\< wagePerPiece\<\<" quantity "\<\<quantity; cout\<\<" eared \$" \<\< earnings() \<\<endl;
}
private:

double wagePerPiece;
int quantity;

};
void main()
{
Employee * employ[3] ;
int i;
employ\[0\] = new Manager( 10135, "ZhangSan", 1200 ) ;
employ\[1\] = new HourlyWorker( 30712, "LiSi", 5, 260 ) ;
employ\[2\] = new PieceWorker( 20382, "Wangwu", 0.5, 2850 ) ;
cout << setiosflags(ios::fixed|ios::showpoint) << setprecision(2) ;
for( i = 0; i \<3; i ++ ) employ\[i\] -\> print() ;
for( i = 0; i \< 3; i ++ )
cout \<\<setw(8)\<\< employ\[i\]-\>getName() \<\< " " \<\<setw(10)\<\< employ\[i\] -\> earnings() \<\< endl ;

}
setiosflags(ios::fixed|ios::showpoint) 会使输出以固定小数点表示法显示,而不是使用科学计数法,并且总是显示小数点后的零。这个操作符作用于后续的浮点数输出。

setprecision(2) 设置输出浮点数的精度为2位小数。这意味着输出的浮点数将保留2位小数进行显示。
------------------------------------模式设置结束
10135 ZhangSan Manager
30712 LiSi Hours Worker
wageperhour 5.00 Hours 260.00 earned $1300.00
20382 Wangwu Piece Worker
wagePerPiece 0.50 quantity 2850 eared $1425.00
ZhangSan 1200.00
LiSi 1300.00
Wangwu 1425.00

可能需要学习手写setw和setprecision的样式

完善程序

fill in the blanks according to the output

  1. The following program defined a complex class stands for complex number. It has real part real and imaginary part img. It overloaded complex number addition by using friend function. Please finish it.

    class complex
    {
    float [1], [2]; ---------------------------real img
    public:

    complex (float r=0,float i=0)

    { real=r; img=i; }

    [3] [4] operator+(complex c1,complex c2);---------------------friend complex

    };

    [5] operator+(complex c1,complex c2)-------------------------------complex

    { complex temp;

    [6]---------------------------------------------temp.real=cl.real+c2.real;
    [7]---------------------------------------------同理
    return temp;

    }

2. The following code has the screen output below, please fill in the blanks.

image-20240530004855492

#include <iostream>
#include <math>
using namespace std;
class Power
{
public:
Power(int i)
{
x=i;
}
*__*(8)___void display(){ cout<<"x="\<\<x;} -------virtual
// definition of virtual function protected: int x;

};

class Square: public Power
{
public:

Square(int n):____(9)_________ { } //Constructor of Square void display()
-----------------------------------------------Power(0)

{ _______ *(10)* ___cout\<\<”\tx square=”\<\<x\*x\<\<endl;}------Power::dispaly();

};

class Cube:public Power { public:

Cube(int n):Power(n){ } void display()

{ _______ *(10)* ___; cout\<\<”\tx cube=”\<\<x\*x\*x\<\<endl;}-------------Power::dispaly();

};

void fun(Power &p) { p.display();}

void main()
{
Square squ(2);

Cube cub(3);
fun(squ); fun(cub);

}

手抄

Write program

1.Use function template to calculate average of arrays of different data type. Function main () is as following:

#include <iostream>
using namespace std;
void main()

{
int a[]={ 1,2,3,4,5,6,7,8,9,10 };
double b[]={ 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.0 };
cout\<\< "Average of array a:" \<\<average(a,10)\<\<endl;
cout\<\< "Average of array b:" \<\<average(b,10)\<\<endl;
}

Program calculates average of an array of type integer and of type double. complete a function template to accomplish such function(功能) (6 points )

int average(int* arry,int _max)
{
int temp=0;
for(int i=;i<_max;i++)
{
temp+=arry[i];
}
temp/=_max;
return temp;
}
double average(double* arry,int _max)
{
int temp=0;
for(int i=;i<_max;i++)
{
temp+=arry[i];
}
temp/=_max
return temp;
}

Rewrite class Student, overload operator >> and \<\< to substitute(代替) function input() and output() respectively. (8 points)

  1. Add a constructor for class Student to initiate data members ;(3 points)

  2. Modify function main() to get correct result. (3 points)

#include <iostream> 
using namespace std;
class Student
{
char name[20];
unsigned id;
double score;
public:
void input()
{
cout\<\<"name? ";
cin\>\>name;
cout\<\<"id? ";
cin\>\>id;
cout\<\<"score? ";
cin\>\>score;
}
void output()
{
cout\<\<"name: "\<\<name\<\<"\tid: "\<\<id\<\<"\tscore: "\<\<score\<\<endl;
}
};
int main()
{
Student s; s.input();
s.output();
}
#include <iostream> 
using namespace std;
class Student
{
friend ostream& operator>>(ostream& in,Student&)
friend istream& operator<<(istream& in,Student&)
private:
char name[20];
unsigned id;
double score;
public:
void input()
{
cout\<\<"name? ";
cin\>\>name;
cout\<\<"id? ";
cin\>\>id;
cout\<\<"score? ";
cin\>\>score;
};
ostream& operator>>(ostream& in,Student&)
{
in>>name>>in>>score;
}
void output()
{
cout\<\<"name: "\<\<name\<\<"\tid: "\<\<id\<\<"\tscore: "\<\<score\<\<endl;
}
};
int main()
{
Student s; s.input();
s.output();
}

总结:

1.重载运算符

  1. 纯虚函数和抽象类
  2. 课本上不知名的函数,如此处使用的复制,剪切等
  3. 输出的样式
  4. 生成的顺序