C++学习-类和对象(2)

作者:gzshun. 原创作品,转载请标明出处!
来源:
http://blog.csdn.net/gzshun


类(class)是C++面向对象程序设计的核心,它是实现抽象类型的工具。类是通过抽象数据类型的方法来实现的一种数据类型。类是对某一类对象的抽象,而对象是某一种类的实例。
本文稍微说一下类和对象的基本使用,比较简单也是最基本的C++基础。
一. 类
类的定义有2个部分:声明部分和实现部分。
声明部分:用来声明类中的数据成员和成员函数(方法)。 ->告诉用户"干什么?"。
实现部分:用来对成员函数的定义。 ->告诉用户"怎么干"。


二. 类的关键字

1.public
公有成员,在程序的任何地方都可以被访问。
2.private
私有成员,只能被成员函数和类的友元访问。
3.protected
保护成员,用于继承中。


三. 类的声明

下面只提供最简单的类声明,因为一个真正的类,还会涉及到很多性质或者特点。
本实验是在Code::Blocks工具中进行的,为了规范性,这里总共创建了3个源文件:main.cpp test1.cpp test1.h
main.cpp: 主程序
test1.cpp: test1.h头文件中的类的定义

test1.h: 类的声明

//test1.h #ifndef TEST1_H_INCLUDED #define TEST1_H_INCLUDED class CAnimal { public: int getAge(); void setAge(int age); void addAge(); private: int mAge; }; #endif // TEST1_H_INCLUDED


四. 类的定义
当类的成员函数的函数体在类的外部定义时,必须由作用域运算符"::"来通知编译系统该函数所属的类。

//test1.cpp #include "test1.h" int CAnimal::getAge() { return mAge; } void CAnimal::addAge() { mAge++; } void CAnimal::setAge(int age) { mAge = age; }

五. 对象的定义
CAnimal类的概念已经创建出来,现在就要实例化出一只动物,这里就用阿猫阿狗来举例。以下用2种方式来实例化对象:
1.CAnimal dog; //创建出了一只dog
2.CAnimal *cat = new CAnimal; //动态创建了一只cat
以下贴出使用dog和cat的具体操作:

//main.cpp #include <iostream> #include "test1.h" using namespace std; int main() { //dog CAnimal dog; dog.setAge(12); cout << "Dog is " << dog.getAge() << " years old." << endl; cout << "After one year." << endl; dog.addAge(); cout << "Dog is " << dog.getAge() << " years old." << endl; //cat CAnimal *cat = new CAnimal; cat->setAge(12); cout << "Cat is " << cat->getAge() << " years old." << endl; cout << "After one year." << endl; cat->addAge(); cout << "Cat is " << cat->getAge() << " years old." << endl; return 0; }

六. 程序运行结果

Dog is 12 years old. After one year. Dog is 13 years old. Cat is 12 years old. After one year. Cat is 13 years old.

七. C++中class与struct的区别
在C++面向对象语言中,class和struct的功能很相似,struct也是一种类。
区别:
一个struct也是一个class,但是struct的默认方式是公用部分,而class的默认方式是私用部分。
以下使用代码说明,下面的class与struct是等价的:

class: class CAnimal { //默认是private int mAge; public: int getAge(); void setAge(int age); void addAge(); }; <=> struct: struct CAnimal { //默认是public int getAge(); void setAge(int age); void addAge(); private: int mAge; };

八. 为什么类的定义以分号结束
这是什么问题?有人说我很无聊。
其实并不单单类的定义要以分号结束,C++中的struct也要以分号结束。原因很简单,因为咱们的使用习惯,或者说是编译器编译程序要考虑的情况,在定义之后,可以接一个对象的定义列表,理所当然要以分号结束。
看几个简单的例子:

1.class

class CAnimal { //... }dog, cat;

2.struct

struct CAnimal { //... }dog, cat;

3.int a, b, c; //O(∩_∩)O哈哈~

本博文是非常基础的,由简单循序渐进到复杂,这样才能培养出兴趣与恒心!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值