Problem D: 字符类的封装

本文介绍了一个简单的字符类封装练习,包括无参构造函数、构造函数、设置和获取字符及ASCII码的方法。通过示例展示了如何使用这个类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem D: 字符类的封装

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 1078   Solved: 808
[ Submit][ Status][ Web Board]

Description

先来个简单习题,练练手吧!现在需要你来编写一个Character类,将char这一基本数据类型进行封装。该类中需要有如下成员函数:

1. 无参构造函数。

2. 构造函数Character(char):用参数初始化数据成员。

3. void setCharacter(char):重新设置字符值。

4. int getAsciiCode():返回字符的ASII码。

5. char getCharacter():返回字符值。

6. 析构函数。

Input

输入只有1行,包含一个合法的、可打印的字符。

Output

输出有好多行,请参考样例来编写相应的函数。

Sample Input

c

Sample Output

Default constructor is called!Character a is created!ch1 is c and its ASCII code is 99.ch2 is a and its ASCII code is 97.Character a is erased!Character c is erased!

HINT

Append Code

append.cc,
#include <iostream>
using namespace std;
class Character
{
private:
    char c;
public:
    Character()
    {
        cout<<"Default constructor is called!"<<endl;
    }
    Character(char s)
    {
        cout<<"Character "<<s<<" is created!"<<endl;
        c = s;
    }
    void setCharacter(char x)
    {
        c = x;
    }
    int getAsciiCode(){return c;}
    char getCharacter(){return c;}
    ~Character()
    {
        cout<<"Character "<<c<<" is erased!"<<endl;
    }
};
int main()
{
    char ch;
    Character ch1, ch2('a');
    cin>>ch;
    ch1.setCharacter(ch);
    cout<<"ch1 is "<<ch1.getCharacter()<<" and its ASCII code is "<<ch1.getAsciiCode()<<"."<<endl;
    cout<<"ch2 is "<<ch2.getCharacter()<<" and its ASCII code is "<<ch2.getAsciiCode()<<"."<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值