滚动屏幕是常见的广告形式,屏幕上的通常显示一段文字。使用现有的string类,通过main函数实现广告的循环3次播放,每次播放都把前一次的内容进行累加,如下例子所示。 To work hard, live a good life. To work hard, live a good life. To work hard, live a good life. (1)使用串连接函数实现上诉广告播放; (2)为其添加一个成员函数实现指定字符的统计:统计字符o出现的次数。(可使用字符查找函数)
时间: 2024-03-25 08:41:07 浏览: 10
下面是实现代码:
```
#include <iostream>
#include <string>
using namespace std;
class Advertise {
private:
string ad;
public:
Advertise(string str): ad(str) {}
void play(int times) {
string temp = ad;
for(int i = 1; i < times; i++) {
ad += temp;
}
cout << ad << endl;
}
int countChar(char c) {
int count = 0;
for(int i = 0; i < ad.length(); i++) {
if(ad[i] == c) {
count++;
}
}
return count;
}
};
int main() {
Advertise ad("To work hard, live a good life. ");
ad.play(3);
cout << "The character 'o' appears " << ad.countChar('o') << " times." << endl;
return 0;
}
```
我们定义了一个 Advertise 类,包含广告字符串 ad 和两个成员函数 play 和 countChar。play 函数实现了广告的循环播放,countChar 函数实现了指定字符的统计。
在主函数中,我们创建了一个 Advertise 对象 ad,并调用其 play 函数播放广告,再调用 countChar 函数统计字符 'o' 的出现次数。