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

时间:2024-07-11 20:05:14

准备

1.在VS中新建一个项目-Viscal C++ ---常规--空项目

2.建立一个.h的头文件 定义一个类 声明其成员(C#中的属性和方法)

#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的文件  声明一个类 实现成员变量初始化操作

#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();
Per.setAge();
Per.setName("Tony");
int id = Per.getId();
string name = Per.getName();
int age = Per.getAge();
cout << id <<","<< name <<","<< age<<endl;
system("pause");
return ;

通过指针方式

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;

完成代码例子

#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();
Per->setName("Tommy");
Per->setAge();
int id = Per->getId();
string name = Per->getName();
int age = Per->getAge();
cout << id <<","<< name <<","<< age<<endl;
delete Per;
system("pause");
return ;
}

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