直接看代码吧
#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;
}
/*----------------------------------------------------*/
运行结果:
参考文章:
(完)