(二十四)C++篇-设计类的重复引用

有时候我们希望可以不用重复的调用类名,然后直接给类的字段或属性赋值,如下:

    bobo.setName("bobo")
    .setAge(4)
    .setSex('F')
    .setHobby("Swimming");

测试代码:

#include
#include

using namespace std;

class Dog
{
public:
    Dog& setName(string name);
    Dog& setAge(int age);
    Dog& setSex(char sex);
    Dog& setHobby(string hoppy);

    string name;
    int age;
    char sex;
    string hoppy;
};

Dog& Dog::setName(string name)
{
    this->name = name;
    return *this;
}

Dog& Dog::setAge(int age)
{
    this->age = age;
    return *this;
}

Dog& Dog::setSex(char sex)
{
    this->sex = sex;
    return *this;
}

Dog& Dog::setHobby(string hoppy)
{
    this->hoppy = hoppy;
    return *this;
}

int main()
{
    Dog bobo; 
    bobo.setName("bobo")
    .setAge(4)
    .setSex('F')
    .setHobby("Swimming");

    cout<

输出结果:

tekken@tekken:~/C++WS$ ./a.out 
bobo ,age: 4 ,sex: F ,hoppy: Swimming

你可能感兴趣的:((二十四)C++篇-设计类的重复引用)