博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 通过对象方式 、指针方式两种方式去访问成员变量(属性或者方法)
阅读量:4498 次
发布时间:2019-06-08

本文共 2026 字,大约阅读时间需要 6 分钟。

准备

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

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

#include
#include
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<

 

通过指针方式

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<
View Code

 

 

 

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

你可能感兴趣的文章
Palindrome Partitioning
查看>>
Microservice架构模式简介
查看>>
换种形式工作
查看>>
javascript中三种典型情况下this的含义
查看>>
Python学习笔记day2(python基础一)
查看>>
【QC】安装
查看>>
628. Maximum Product of Three Numbers
查看>>
log4j Spring aop 注解的日志管理
查看>>
Spring cloud实战 从零开始一个简单搜索网站_Hystrix断路由的实现(三)
查看>>
Android服务Service
查看>>
sqlalchemy学习(一)
查看>>
silverlight Image Source URI : 一个反斜杠引发的血案
查看>>
Windows Phone开发(35):使用Express Blend绘图 转:http://blog.csdn.net/tcjiaan/article/details/7493010...
查看>>
Windows Phone开发(33):路径之其它Geometry 转:http://blog.csdn.net/tcjiaan/article/details/7483835...
查看>>
Android入门(9)AudioRecord和AudioTrack类的使用【转】http://blog.sina.com.cn/s/blog_6309e1ed0100j1rw.html...
查看>>
mybatis整合Spring编码
查看>>
第七章 路由 68 路由-前端路由和后端路由的概念
查看>>
dpkg包管理
查看>>
前端JS利用canvas的drawImage()对图片进行压缩
查看>>
一键切换皮肤的解决思想及iframe嵌套时寻找下级iframe的方法
查看>>