準備ios
1.在VS中新建一個項目-Viscal C++ ---常規--空項目ide
2.創建一個.h的頭文件 定義一個類 聲明其成員(C#中的屬性和方法)this
#include<iostream> #include<string> using namespace std; class Person { public: void setId(int id); int getId(); void setName(string name); string getName(); void setAge(int age); int getAge(); private: int _id; string _name; int _age; };
創建一個.cpp的文件 聲明一個類 實現成員變量初始化操做spa
#include "Per.h"; using namespace std; void Person::setId(int id){ this->_id = id; } void Person::setName(string name){ this->_name = name; } void Person::setAge(int age){ this->_age= age; } int Person::getId(){ return this->_id; } string Person::getName(){ return this->_name; } int Person::getAge(){ return this->_age; } int main(){ }
經過對象方式指針
Person Per; Per.setId(1); Per.setAge(25); Per.setName("Tony"); int id = Per.getId(); string name = Per.getName(); int age = Per.getAge(); cout << id <<","<< name <<","<< age<<endl; system("pause"); return 0;
經過指針方式code
Person *Per = new Person();
Per->setId(1);
Per->setName("Tommy");
Per->setAge(20);
int id = Per->getId();
string name = Per->getName();
int age = Per->getAge();
cout << id <<","<< name <<","<< age<<endl;
delete Per;
system("pause");
return 0;對象
完成代碼例子blog
#include "Per.h"; using namespace std; void Person::setId(int id){ this->_id = id; } void Person::setName(string name){ this->_name = name; } void Person::setAge(int age){ this->_age= age; } int Person::getId(){ return this->_id; } string Person::getName(){ return this->_name; } int Person::getAge(){ return this->_age; } int main(){ //1.經過對象方式訪問 //Person Per; //Per.setId(1); //Per.setAge(25); //Per.setName("Tony"); //int id = Per.getId(); //string name = Per.getName(); //int age = Per.getAge(); //2.經過指針方式訪問 Person *Per = new Person(); Per->setId(1); Per->setName("Tommy"); Per->setAge(20); int id = Per->getId(); string name = Per->getName(); int age = Per->getAge(); cout << id <<","<< name <<","<< age<<endl; delete Per; system("pause"); return 0; }