关于CPP类中字符串成员初始化

直接看代码吧

#include <iostream>
#include <string>

/*
A string is actually an object of the C++ Standard Library class string. 
This class is defined in header <string>, and the name string, like cout, belongs to namespace std.
To enable string-relative-statement compile, includes the <string> header.
The using directive in "using namespace std;" allows us to simply write string rather than std::string.
For now, you can think of string variables like variables of other types such as int.

The class template basic_string provides typical string-manipulation operations such as
copying, searching, etc.
The template definition and all support facilities are defined in namespace std; 
these include the typedef statement "typedef basic_string< char > string;"that creates the alias type string
for basic_string<char>. To use strings, include header <string>.
*/

using std::cout;
using std::cin;
using std::endl;
using std::string;


/*----------------------------------------------------*/

class Cat
{
    private:
        std::string _name = "Mogo";
        int _age = 20;

    public:

    Cat(string name)
    {
        if(name.length() < 5)
            _name = "hehda dsa  You!";
        else
             _name = name;
    }


    //使用初始化列表通常是首选方法
    //因为它更高效,并且可以避免在构造函数体内对std::string等类型进行复制操作时产生的额外开销。 
    Cat():_name("DanDan")
    {
        _age = 100;
    }

    Cat(int age):_name(4, 'Y'), _age(age) {}

    string shout(void)
    {
        return "my name is " + _name + " \"MI\"";
    }

    void show(void)
    {
        cout << "Age is: " << std::hex << _age << endl;
    }
};


/*----------------------------------------------------*/

int main()
{
    std::cout<<"Hello, World!"<<std::endl;

    Cat cat = Cat("Ista");
    Cat l_cat = Cat();
    Cat h_cat = Cat(255);

    cout << cat.shout() << endl;
    cout << l_cat.shout() << endl;
    cout << h_cat.shout() << endl;

    cat.show();
    l_cat.show();
    h_cat.show();

    string pre_firm("borgward");
    string rep_pos(8, 'X');

    cout << pre_firm << "---" << rep_pos << endl;

    return 0;
}

/*----------------------------------------------------*/

运行结果:

参考文章:

C++类成员的初始化_c++ 类成员初始化-CSDN博客

(完)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

issta

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值