用c++,构造一个类,类内实现以下功能: 打印乘法表
时间: 2024-05-14 11:19:41 浏览: 14
好的,这是一个简单的示例代码:
```c
#include <stdio.h>
// 定义一个类
typedef struct _MultTable {
// 成员函数,打印 n 行的乘法表
void (*print)(struct _MultTable* self, int n);
} MultTable;
// 打印乘法表的实现
void printTable(MultTable* self, int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("%d*%d=%d\t", j, i, i*j);
}
printf("\n");
}
}
int main() {
// 创建一个 MultTable 类的实例
MultTable table;
// 设置成员函数
table.print = &printTable;
// 调用成员函数打印乘法表
table.print(&table, 9);
return 0;
}
```
注意,在 C 语言中没有类的概念,通常可以通过使用结构体和函数指针来模拟类和成员函数的实现。上面的代码定义了一个名为 MultTable 的结构体,其中定义了一个 print 函数指针成员,用于打印乘法表。在主函数中,先创建了一个 MultTable 结构体的实例,并设置了 print 函数指针成员的值为 printTable 函数的地址。最后通过调用实例的成员函数来打印乘法表。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)