描述
程序填空,输出指定结果
#include
#include
#include
#include
using namespace std;
class MyString:public string
{
// 在此处补充你的代码
};
int main()
{
MyString s1("abcd-"),s2,s3("efgh-"),s4(s1);
MyString SArray[4] = {"big","me","about","take"};
cout << "1. " << s1 << s2 << s3<< s4<< endl;
s4 = s3;
s3 = s1 + s3;
cout << "2. " << s1 << endl;
cout << "3. " << s2 << endl;
cout << "4. " << s3 << endl;
cout << "5. " << s4 << endl;
cout << "6. " << s1[2] << endl;
s2 = s1;
s1 = "ijkl-";
s1[2] = 'A' ;
cout << "7. " << s2 << endl;
cout << "8. " << s1 << endl;
s1 += "mnop";
cout << "9. " << s1 << endl;
s4 = "qrst-" + s2;
cout << "10. " << s4 << endl;
s1 = s2 + s4 + " uvw " + "xyz";
cout << "11. " << s1 << endl;
sort(SArray,SArray+4);
for( int i = 0;i < 4;i ++ )
cout << SArray[i] << endl;
//s1的从下标0开始长度为4的子串
cout << s1(0,4) << endl;
//s1的从下标5开始长度为10的子串
cout << s1(5,10) << endl;
return 0;
}
输入
无
输出
1. abcd-efgh-abcd-
2. abcd-
3.
4. abcd-efgh-
5. efgh-
6. c
7. abcd-
8. ijAl-
9. ijAl-mnop
10. qrst-abcd-
11. abcd-qrst-abcd- uvw xyz
about
big
me
take
abcd
qrst-abcd-
继承后需要构建的:
1.无参构造函数
2.有参构造函数
3.复制构造函数
// 在此处补充你的代码
public:
MyString():string(){};
//无参构造函数——调用string的无参构造函数
MyString(const char *s): string(s){};
//有参构造函数——调用string的有参构造函数
MyString(const string &s): string(s){};
//复制函数——调用string的复制函数
MyString operator()(int s,int l)
//重构(),需要调用substr函数
{
return substr(s,l);
//用string中给的substr函数
}
//能在string对象上操作的,都能在MyString对象上操作
//[]继承
//+继承
//=继承
//+=继承
//()需要调用substr函数,故在MyString中也需要设置一下
//
描述
代码填空,使得程序能够自动统计当前各种动物的数量
#include
using namespace std;
// 在此处补充你的代码
void print() {
cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
int main() {
print();
Dog d1, d2;
Cat c1;
print();
Dog* d3 = new Dog();
Animal* c2 = new Cat;
Cat* c3 = new Cat;
print();
delete c3;
delete c2;
delete d3;
print();
}
输入
无
输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
补充的代码
不用虚函数猫的数量不对,虚函数在之后的课程讲解。
class Animal{
public:
static int number;
Animal(){ //调用构造函数,number++
number++;
}
virtual~Animal(){ //调用析构函数,number--
number--;
}
};
class Dog:public Animal{ //派生类调用,也会调用基类
public:
static int number;
Dog(){
number++;
}
~Dog(){
number--;
}
};
class Cat:public Animal{
public:
static int number;
Cat(){
number++;
}
~Cat(){
number--;
}
};
int Dog::number=0;
int Animal::number=0;
int Cat::number=0;
全局中初始化静态变量的值,
要注明是基类还是派生类::