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;
}