27 C++ 基础—类和对象的使用

1.对象成员的使用

1.1 第一种方法:访问对象
    // 第一种方法:访问对象
    Student mStudent;
    mStudent.setName("李白");
    result = mStudent.getName();
    cout<<"Name : " << result << endl;
1.2 第二种方法:通过指针进行方法
    // 第二种方法:通过指针进行方法
    Student* p = &mStudent;
    result = p->getName();
    cout<<"Name : " << result << endl;
1.3 第三种方法:通过引用进行访问
    // 第三种方法:通过引用进行访问
    Student &s = mStudent;
    result = s.getName();
    cout<<"Name : " << result << endl;
    return 0;
1.4 demo
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Student {
public:
    void setName(string vaule){
        name = vaule;
    }

    string getName() {
        return name;
    }

private:
    string name;
};

int main() {

    string result;

    // 第一种方法:访问对象
    Student mStudent;
    mStudent.setName("李白");
    result = mStudent.getName();
    cout<<"Name : " << result << endl;

    // 第二种方法:通过指针进行方法
    Student* p = &mStudent;
    result = p->getName();
    cout<<"Name : " << result << endl;

    // 第三种方法:通过引用进行访问
    Student &s = mStudent;
    result = s.getName();
    cout<<"Name : " << result << endl;
    return 0;
}

2.类和实现的分离

2.1 定义头文件

主要放对象的声明

#ifndef STUDENT_H
#define STUDENT_H

#include <iostream>
#include <string>

using namespace std;

// 放置声明
class Student {
public:
    void setName(string vaule);
    string getName();

private:
    string name;
};
#endif
2.2 对象的实现
#include "Student.h"
#include <string>

string Student :: getName() {
    return name;
}

void Student ::setName(string vaule){
    name = vaule;
}
2.3 访问对象
#include <iostream>
#include "Student.h"

int main() {
    Student mStudent;
    mStudent.setName("李白");
    cout<<"Name : " << mStudent.getName() << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值