写在前面:copyer永远打不过coder,希望大家能够独立写出程序,仅仅将我的编码思路作为参考,毕竟还有最后期末考试
题目:
采用面向对象方法编写程序实现如下功能,程序中不能include任何与字符串操作有关的头文件:
1、定义基类mystring,成员变量为char* s,该变量在构造函数中初始化,访问属性为protected,使子类可以继承。成员函数
int getlen(),返回字符串的长度。
2、定义派生类digitstring继承mystring,派生类中没有成员变量,继承父类的成员变量,派生类中定义函数int
getvalue(),计算字符串中数字的乘积。
3、在main()函数中,要求用户输入一串只包含数字的字符串,在主程序中判断用户输入是否合法,只保存用户输入的数组,用户输入回车键表示输入结束。创建digitstring对象,计算得到数组乘积返回主程序显示输出。
参考:
#include <iostream>
using namespace std;
bool isDigit(char* character) //判断是不是数字
{
return (*character >= 48 && *character <= 57) ? true : false; //在ASCII,048对应‘0’,057对应‘9’,详见大一上学期课本357页
}
class mystring {
protected:
char* s;
public:
mystring(char* pointer) {
s = pointer;
}
int getlen() {
int counter = 0;
for (int i = 0; *(s+i)!= 0; i++) {
counter++;
}
return counter;
}
};
class digitstring :public mystring
{
public:
digitstring(char* pointer) :mystring(pointer) {};
int getvalue() {
int product = 1;
int len = getlen();
for (int i = 0; i < len; i++) {
if (isDigit((s + i))) {
product *= (*(s + i)-48); //char字符‘0’和int数字0相差了48
}
}
return product;
}
};
int main(void)
{
char c[100];
cout << "Please enter a string of pure numbers : ";
cin >> c;
cout << "The product of these numbers is : ";
digitstring D(c);
cout << D.getvalue() << endl;
return 0;
}