day7: homework

This commit is contained in:
flykhan 2023-08-01 22:54:37 +08:00
parent c127a3a81b
commit 15ae1803d7
2 changed files with 168 additions and 0 deletions

43
day7/homework/h6.cpp Normal file
View File

@ -0,0 +1,43 @@
// 请完成以下程序的代码,实现数组的循环迭代
#include <iostream>
using namespace std;
template <typename T>
class Iterator
{
public:
T *data;
int size;
int currentIndex;
public:
Iterator(T *d, int s) : data(d), size(s), currentIndex(0) {}
T getCurrent() // 获取当前元素
{
return data[currentIndex];
}
void next() // 迭代器前进的代码
{
currentIndex = (currentIndex + 1) % size; // 对 size 取余用于循环
}
void previous() // 迭代器后退的代码
{
currentIndex = (currentIndex - 1 + size) % size; // + size 用于防止负数,对 size 取余用于循环
}
};
int main()
{
int *p = new int[5]{1, 2, 3, 4, 5}; // 创建数组
Iterator<int> it(p, 5); // 创建迭代器对象
int cnt = 0; // 计数器,用于控制循环次数
while (cnt++ < 5)
{
cout << it.getCurrent() << endl; // 输出当前元素
it.next(); // 迭代器前进
}
return 0;
}

125
day7/homework/h7.cpp Normal file
View File

@ -0,0 +1,125 @@
/********************************************************************
Animal Cat Dog : class Animal
{
public:
virtual ~Animal() {}
};
class Cat : public Animal
{
public:
void meow()
{
std::cout << "Meow!" << std::endl;
}
};
class Dog : public Animal
{
public:
void bark()
{
std::cout << "Woof!" << std::endl;
}
};
1) main Animal 使 dynamic_cast Cat meow "Meow!"
2) main Animal 使 dynamic_cast Dog bark "Woof!"
3) main Cat 使 dynamic_cast Animal
4) main Dog 使 dynamic_cast Animal
try
{
}
catch (int e)
{
}
********************************************************************/
#include <iostream>
using namespace std;
class Animal
{
public:
virtual ~Animal() {}
};
class Cat : public Animal
{
public:
void meow()
{
cout << "Meow!" << endl;
}
};
class Dog : public Animal
{
public:
void bark()
{
cout << "Woof!" << endl;
}
};
int main()
{
Animal *ap = new Animal(); // 创建一个 Animal 类型的指针
try
{
Cat *cp = dynamic_cast<Cat *>(ap); // 将其转换为 Cat 类型的指针
cp->meow();
}
catch (int e)
{
cout << "dynamic_cast 将 Animal 转换为 Cat 失败" << endl
<< e << endl;
}
Animal *ap2 = new Animal(); // 创建一个 Animal 类型的指针
try
{
Dog *dp = dynamic_cast<Dog *>(ap2); // 将其转换为 Dog 类型的指针
dp->bark();
}
catch (int e)
{
cout << "dynamic_cast 将 Animal 转换为 Dog 失败" << endl
<< e << endl;
}
Cat *cp2 = new Cat(); // 创建一个 Cat 类型的指针
try
{
Animal *ap3 = dynamic_cast<Animal *>(cp2); // 将其转换为 Animal 类型的指针
cout << "dynamic_cast 将 Cat 转换为 Animal 成功" << endl;
}
catch (int e)
{
cout << "dynamic_cast 将 Cat 转换为 Animal 失败" << endl
<< e << endl;
}
Dog *dp2 = new Dog(); // 创建一个 Dog 类型的指针
try
{
Animal *ap4 = dynamic_cast<Animal *>(dp2); // 将其转换为 Animal 类型的指针
cout << "dynamic_cast 将 Dog 转换为 Animal 成功" << endl;
}
catch (int e)
{
cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl
<< e << endl;
}
return 0;
}