第五章习题

本文展示了C++中类的构造函数、友元运算符重载的使用,以及字符串处理的实现。程序创建了类A,通过自增和自减运算符重载实现成员变量x的增减,并打印结果。另外,类Words演示了如何创建一个包含字符串处理的类,包括构造函数、字符访问和显示方法。最后,类Length将米转换为千米并输出结果。

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

第五章习题

7、写出下列程序的运行结果。

#include <iostream>
    using namespace std;
class A
{
public:
    A(int i) : x(i) {}
    A() { x = 0; }
    friend A operator++(A a);
    friend A operator--(A &a);
    void print();

private:
    int x;
};
A operator++(A a)
{
    ++a.x;
    return a;
}
A operator--(A &a)
{
    --a.x;
    return a;
}
void A::print() { cout << x << endl; }
int main()
{
    A a(7);
    ++a;
    a.print();
    --a;
    a.print();
    return 0;
}
  1. 写出下列程序的运行结果。
#include <iostream>
    using namespace std;
class Words
{
public:
    Words(char *s)
    {
        str = new char[strlen(s) + 1];
        strcpy(str, s);
        len = strlen(s);
    }
    void disp();
    char operator[](int n);

private:
    int len;
    char *str;
};
char Words::operator[](int n)
{
    if (n < 0 || n > len - 1)
    {
        cout <<”数组下标越界!\n”;
        return  ‘ ‘;
        else return *(str + n);
    }
    void Words::disp() { cout << str << endl; }
    int main()
    {
        Words word(“This is C++ book.);
        word.disp();
        cout <<”第1个字符:”;
        cout << word[0] << endl;
        cout <<”第16个字符:”;
        cout << word[15] << endl;
        cout <<”第26个字符:”;
        cout << word[25] << endl;
        return 0;
    }
9. 写出下列程序的运行结果。
#include <iostream>
        using namespace std;
    class Length
    {
        int meter;

    public:
        Length(int m) { meter = m; }
        operator double() { return (1.0 * meter / 1000); }
    };
    int main()
    {
        Length a(1500);
        double m = float(a);
        cout <<”m =<< m <<”千米”<< endl;
        return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值