从数组、结构到类的过渡例子(char []到string)

本文通过对比char数组和string类的使用,展示了面向对象编程中string类带来的灵活性和便利性,特别是通过string类的方法如size(), length(), capacity()等进行字符串属性操作。

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


如何从面向过程到面向对象中的第一个问题就是从一个数组或者结构引申出类,告诉大家使用类这个新的概念有什么用,


明天就用char []到string作一次引申。例子如下:


#include <iostream>
#include <numeric>
#include <cstring>
using namespace std;

void PrintAttribute(string &str)
{
    cout<<"size: "<<str.size()<<endl;
    cout<<"length: "<<str.length()<<endl;
    cout<<"capacity: "<<str.capacity()<<endl;
    cout<<"max size: "<<str.max_size()<<endl;
}

int main()
{
    char cs1[]="test cs1";
    char cs2[]="test cs2";
    char *cs3=new char[strlen(cs1)+1];
    strcpy(cs3,cs1);

    cs1+=cs2;

    cout<<cs1<<endl;
    cout<<cs2<<endl;

    string s1;
    PrintAttribute(s1);
    cout<<"================================"<<endl;
    s1="My String object";
    cout<<s1<<endl;

    string s2;
    s2="My String2 object";
    cout<<s2<<endl;

    s2+=s1;
    cout<<s2<<endl;

    PrintAttribute(s1);

}


//通过比较cs1+=cs2和s2+=s1这两种形式的区别,看出有了类这个概念之后,代码的编写方式更加的灵活。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值