C++ 老九 带参构造 P97

本文详细介绍了使用C++实现的学生类构造过程,包括默认构造函数、带参数构造函数及显示类型构造函数的定义与使用。同时,深入探讨了成员变量的初始化、成员函数的实现以及通过指针调用成员函数的方法。

Main

#include <iostream>
#include "LandOwnerv4.h"
#include "Student.h"
using namespace std;

int main() {
    Student stu1;
    Student stu2(" dennis ", "Got a name ");
    Student stu3(6);
    stu2.ShowInfo();
    auto* stu5 = new Student(" Charling ", " Is a girl ");   //这里本来是,程序自动更新  Student* stu5 = new Student(" Charling ", " Is a girl ");   定义一个指针

    stu5->ShowInfo();   //指针调用


    return 0;
}

头文件

//
// Created by llb on 2020/4/22.
//

#ifndef CLASS_EXERCISE_STUDENT_H
#define CLASS_EXERCISE_STUDENT_H
#include <string>
#include <iostream>

using namespace std;
class Student {
private:
    string m_name;
    string m_describe;
    int m_age{};
public:
    const string &getMName() const;

    void setMName(const string &mName);

    const string &getMDescribe() const;

    void setMDescribe(const string &mDescribe);

    int getMAge() const;

    void setMAge(int mAge);

    Student();
    Student(string name, string describe);
    explicit Student(int age);
    void ShowInfo();
};


#endif //CLASS_EXERCISE_STUDENT_H

构造函数

//
// Created by llb on 2020/4/22.
//

#include "Student.h"

const string &Student::getMName() const {
    return m_name;
}

void Student::setMName(const string &mName) {
    m_name = mName;
}

const string &Student::getMDescribe() const {
    return m_describe;
}

void Student::setMDescribe(const string &mDescribe) {
    m_describe = mDescribe;
}

int Student::getMAge() const {
    return m_age;
}

void Student::setMAge(int mAge) {
    if (mAge < 0) {
        m_age = 18;
    } else {
        m_age = mAge;
    }
}

Student::Student() {
    cout << "default info" << endl;
}

Student::Student(string name, string describe) {
    setMName(name);  //equal to:   m_name = name;
    setMDescribe(describe);
    cout << "has name and describe parameters" << endl;
}

Student::Student(int age) {
    setMAge(age);
    cout << "has age parameters" << endl;
}

void Student::ShowInfo() {
cout << m_describe  <<  m_name  << "   pppppp" << endl;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值