定义一个类Array,实现对字符数组元素的基本操作。 私有数据: char a[100]; char b[100]; 公有成员函数: Array(char c[],char d[]);// 为数据成员初始化。 void fun();//将b拼接到a的后面。 不用拼接函数 void print();//输出两个字符串 在主函数中用类Array定义对象arr,并用arr调用成员函数。 char m[100]={"apple"}; char n[100]={"tree"};
时间: 2024-02-29 14:51:45 浏览: 27
好的,以下是实现题目要求的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Array {
private:
char a[100];
char b[100];
public:
Array(char c[], char d[]) {
strcpy(a, c);
strcpy(b, d);
}
void fun() {
int len_a = strlen(a);
int len_b = strlen(b);
for (int i = 0; i < len_b; i++) {
a[len_a + i] = b[i];
}
}
void print() {
cout << "a: " << a << endl;
cout << "b: " << b << endl;
}
};
int main() {
char m[100] = {"apple"};
char n[100] = {"tree"};
Array arr(m, n);
arr.fun();
arr.print();
return 0;
}
```
输出结果为:
```
a: appletree
b: tree
```
注意,我们可以使用 `strcpy` 函数来复制字符串,包括将字符串拼接到另一个字符串的末尾。此外,在 `fun()` 函数中,我们需要先获取两个字符串的长度,然后将 `b` 中的字符一个一个地拼接到 `a` 的末尾。最后,我们在 `main()` 函数中创建了一个 `Array` 对象,并调用了成员函数 `fun()` 和 `print()`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)