上一篇
类入门
#include <iostream>
#include <string>
using namespace std;
class Dog;
class Cat
{
friend istream &read(istream &, Cat &item);
public:
Cat() = default;
Cat(const int &a) : Age(a) {}
Cat(const int &a, const string &s) : Age(a), Name(s) {}
Cat(istream &is);
int age() const
{
access_num++;
return this->Age;
}
int sex() const
{
access_num++;
return this->Sex;
}
string name() const
{
return this->Name;
}
Cat& setName(string name);
Cat& setAge(const int age);
void inlineTest();
inline void inlineTest2();
private:
int Sex = 1;
int Age;
string Name;
mutable size_t access_num;
};
Cat::Cat(istream &is)
{
read(is, *this);
}
inline void Cat::inlineTest()
{
cout << "内联方式2:类中声明不加inline,类外定义加inline" << endl;
}
void Cat::inlineTest2()
{
cout << "内联方式3:只在类中声明加inline" << endl;
}
Cat& Cat::setName(string name)
{
Name = name;
return *this;
}
Cat& Cat::setAge(int age)
{
Age = age;
return *this;
}
istream &read(istream &is, Cat &item)
{
is >> item.Age >> item.Name >> item.Sex;
return is;
}
ostream &print(ostream &os, const Cat &item)
{
os << "名称:" << item.name() << "\t年龄:" << item.age();
return os;
}
int main()
{
Cat c;
print(cout, c.setName("千任雪").setAge(18));
c.inlineTest();
cout << c.sex() << endl;
return 0;
}
作用域
int big;
class Scope
{
public:
typedef string::size_type index;
index test(index a, int big) const;
private:
int Age;
int big;
};
Scope::index Scope::test(index a, int big) const {
int t = ::big;
return this->Age;
}
|