C++ 经过对象方式 、指针方式两种方式去访问成员变量(属性或者方法)

准备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;
}
View Code

 

 

 

相关文章
相关标签/搜索