聲明和實現,OC裏面是.h和.m文件是聲明和實現分離的,
若想其餘文件引用此文件的方法或是屬性,得在.h 上聲明一下。
複製代碼
// 聲明 .hpp 頭文件
class Person {
int m_age; //屬性
public:
Person(); //構造函數
~Person(); //析構函數
void setAge(int age); //setAge函數
int getAge(); //getAge函數
};
// 實現 .cpp
#include "Person.hpp"
#include <iostream>
using namespace std;
// ::是域運算符
// 實現 .cpp 源文件
Person::Person() {
cout << "Person()" << endl;
}
Person::~Person() {
cout << "~Person()" << endl;
}
void Person::setAge(int age) {
this->m_age = age;
}
int Person::getAge() {
return this->m_age;
}
//在main.cpp中
#include <iostream>
#include "Person.hpp"
using namespace std;
int main() {
Person person;
person.setAge(20);
cout << person.getAge() << endl;
getchar();
return 0;
}
打印結果:
Person()
20
和OC實現一模一樣
複製代碼
::的做用就是告訴編譯器被修飾的成員屬於哪一個類(對象):
1.定義時。類體外定義的要用::修飾,否則會看成沒有定義。
2.訪問時。指定編譯器在某個類的類域中查找某函數,否則有可能找不到。
複製代碼
完整代碼demo,請移步GitHub:DDGLearningCppios