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

本文介绍了如何在C++中创建一个简单的Person类,并通过对象和指针两种方式来访问和使用该类的方法及属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备

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

 

通过指针方式

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(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

 

 

 

转载于:https://www.cnblogs.com/DemoLee/p/4230387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值