C++:类与对象入门 Intro to Class and Object

发布时间:2014-10-23 23:23:40
来源:分享查询网

    我感觉已经很久都没有写过工程相关的东西了,大一学的C++的知识几乎都要忘光了。考虑到还有半年就毕业,我想抓紧最后的时间,再把之前的东西好好看看,在这个博客上简短的记录一些。不仅仅是C++,JAVA、编译、数据库、OS的东西我也会写一些东西放到这里。     作为C++回忆的开始,我打算从类和对象的一些简单知识入手。     先看如下的代码。First, let's look at the following codes. //Book.h #pragma once #include <string> using namespace std; class Book { public: Book(void); Book(string); void setName(string); string getName(); void display(); ~Book(void); private: string bookName; };     数据成员bookName,设为private的话,只有类内成员函数可见。这种写法是工程的写法,他人只能通过接口——设置函数setName和获取函数getName修改bookName,而不能在类外直接修改该数据成员。     两个构造函数Book,用来创建对象,可重载,可以不带参也可以带各种参,只要你把该赋值的赋上就行。可以写个set函数直接用。     析构函数~Book暂时没派上用场,它的用途主要是对象销毁前需要做的事,一般是回收内存,C++可不像JAVA有垃圾回收机制。     另外,我这种写法把接口和实现分隔开来,也是工程的写法。他人看了加了注释的头文件就会一目了然。     类与对象的关系,就像是integer与1、2这样的数字的关系,1这个值是其本身,是对象,integer是类型,是它所属的类。有些哲学意味。     Private data member bookName is only visible within the class. It's an engineering writing style. Others only can through the interface - function setName and getName - to modify bookName, but not directly modify outside the class.     Two construct functions Book are used to create objects. Construct function can be overloaded, with a variety of parameters or none of them, as long as you set the variables in the right places. You can write a function set used in it directly.    Destruct function ~Book seems not work. It's main use is do something before destroying the object, usually free the memory.  C++ does not like JAVA which has garbage collection mechanism.     Also, I separate the interface and implementation, which also belongs to engineering style. Others can understand it easily with a noted head file.     The relationship between classes and objects, just like the type "integer" compares with the number 1,2 with certain value. "1" is its own value, just like an object. However, integer is the type that number "1" belongs to. There is something philosophical, isn't it? //Book.cpp #include "Book.h" Book::Book(void) { } Book::Book(string name) { setName(name); } void Book::setName(string name) { bookName = name; } string Book::getName() { return bookName; } void Book::display() { printf("Welcome!\n"); } Book::~Book(void) { } //main.cpp #include <iostream> #include "Book.h" using namespace std; int main() { Book book1 = Book(); Book book2 = Book("CPP"); book1.setName("JAVA"); book1.display(); cout << book1.getName() << ' ' << book2.getName() << endl; return 0; }

返回顶部
查看电脑版