printinfo函数
时间: 2023-08-09 19:10:25 浏览: 1091
printinfo函数是一个可变参数函数,它可以接受不同数量的参数。如果在函数调用时没有指定参数,它就是一个空元组。如果传递了多个参数,它们将被打印出来。[1]另外,如果在函数调用时使用了两个星号**,参数将以字典的形式导入。[2]这意味着可以通过键值对的方式传递参数。例如,printinfo(1, a=2, b=3)将打印出1和一个包含键值对a=2和b=3的字典。[2]此外,还可以定义一个名为printInfo的函数,它可以完成打印信息的功能。[3]
相关问题
借助虚析构函数编写以下程序:基类 Shape,其中定义了一个虚函数 printInfo() 。 两个派生类 Rectangle 和 Circle , 它们都重写 了 prinfInfo() 函数。使用基类指针数组来存储 Rectangle 和 Circle 对 象的地址,并依次调用它们的 printInfo() 函数。使用 delete 运算符来 删除指向 Shapes 对象的指针,需要使用虚析构函数以确保正确地调 用派生类的析构函数。
以下是程序代码:
```c++
#include <iostream>
using namespace std;
class Shape{
public:
virtual void printInfo(){
cout << "This is a shape." << endl;
}
virtual ~Shape(){};
};
class Rectangle: public Shape{
public:
void printInfo(){
cout << "This is a rectangle." << endl;
}
~Rectangle(){
cout << "Rectangle destructor called." << endl;
}
};
class Circle: public Shape{
public:
void printInfo(){
cout << "This is a circle." << endl;
}
~Circle(){
cout << "Circle destructor called." << endl;
}
};
int main(){
Shape* shapes[2];
shapes[0] = new Rectangle();
shapes[1] = new Circle();
for(int i=0; i<2; i++){
shapes[i]->printInfo();
delete shapes[i];
}
return 0;
}
```
程序首先定义了一个基类 Shape,其中定义了一个虚函数 printInfo()。然后定义了两个派生类 Rectangle 和 Circle,它们都重写了 printInfo() 函数。
程序接着定义了一个 Shape 类型的指针数组 shapes,用来存储 Rectangle 和 Circle 对象的地址。接下来使用循环依次调用它们的 printInfo() 函数,并使用 delete 运算符来删除指向 Shapes 对象的指针。需要使用虚析构函数来确保正确地调用派生类的析构函数。
程序输出结果为:
```
This is a rectangle.
Rectangle destructor called.
This is a circle.
Circle destructor called.
```
可以看到,程序成功地调用了派生类的析构函数。这是因为基类 Shape 的析构函数被声明为虚析构函数,这样在删除指向派生类对象的基类指针时就会调用派生类的析构函数。
定义一个基类Person,数据成员包含姓名,性别,年龄。成员包含函数set()用于初始化数据成员、成员函数Print()用于输出信息。从Person类公有派生出Student类,增加整型数据成员number用于保存学号,函数成员set1()用于初始化数据成员、成员函数PrintInfo()用于输出学生信息。要求:在PrintInfo()函数中调用基类的成员函数Print ()。创建学生对象完成初始化信息及输出。
好的,以下是C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义基类Person
class Person {
protected:
string name; // 姓名
char sex; // 性别
int age; // 年龄
public:
// 初始化数据成员
void set(string n, char s, int a) {
name = n;
sex = s;
age = a;
}
// 输出信息
void Print() {
cout << "姓名:" << name << endl;
cout << "性别:" << sex << endl;
cout << "年龄:" << age << endl;
}
};
// 从Person类公有派生出Student类
class Student : public Person {
private:
int number; // 学号
public:
// 初始化数据成员
void set1(string n, char s, int a, int num) {
set(n, s, a); // 调用基类的成员函数set()
number = num;
}
// 输出学生信息
void PrintInfo() {
Print(); // 调用基类的成员函数Print()
cout << "学号:" << number << endl;
}
};
int main() {
// 创建学生对象并初始化信息
Student s;
s.set1("张三", 'M', 18, 1001);
// 输出学生信息
s.PrintInfo();
return 0;
}
```
输出结果为:
```
姓名:张三
性别:M
年龄:18
学号:1001
```
阅读全文
相关推荐
















