返回 *this 的成员函数以及 const重载

1.非常量成员函数返回非常量 *this,常量成员函数返回常量 *this,指向常量对象。

2.重载函数必须参数数量或者类型不同吗?
答案是:否。还存在一种const重载;
Person.h

#pragma once
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class Person
{
    friend void printInfo(Person person);
private:
    std::string name;
    std::string path;
    void do_display(std::ostream& ou)const { // 此处的const必不可少,否则常量函数无法调用
         ou << name << " " << path << std::endl;
    }

public:
    Person() = default; // 让编译器自动创建一个默认构造函数
    Person(std::string name, std::string path):name(name),path(path){}
    
    std::string getName();
    std::string getPath();

    Person& setName(const string n)
    {
        this->name = n;
        return *this;
    }

    Person& setPath(const string p) // const 重载
    {
        this->path = p;
        return *this;
    }

    const Person& display(std::ostream& ou)const  // const 重载
    {
        do_display(ou);
        return *this;
    }

    Person& display(std::ostream& ou)
    {
        do_display(ou);
        return *this;
    }

    ~Person(){}
};
void printInfo(Person person);
Person.cpp

#include "Person.h"

std::string Person::getName()
{
    return this->name;
}

std::string Person::getPath()
{
    return this->path;
}

void printInfo(Person person)
{
    std::cout << person.name << " " << person.path << std::endl;
}
main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include "Person.h"

using namespace std;

constexpr int f(int a)
{
    constexpr int i = 2;
    //return i;
    return ++a;
}

struct ListNode {
    int val;
    ListNode* next;
};


int main()
{
    const Person p1("qiang", "wei"); // 调用自定义构造函数
    Person p2; // 调用默认构造函数
    
    p2.setName("qiang").setPath("zhuang"); // 由于set函数返回 *this 引用,所以这行代码没错
    p2.display(std::cout); // 调用非常量版本的display
    p1.display(std::cout); // 调用常量版本的display
    
    printInfo(p2); // 友元函数 可以访问 类的私有成员
}

 

posted @ 2020-02-10 20:26  强威  阅读(283)  评论(0编辑  收藏  举报