作为面向对象语言,"一切皆对象",其意义不亚于LINUX下面"一切皆文件".而对象是必须指明其属于哪个类的.类与对象的关系,借用C语言的角度理解的话,如下:
int i,j;
int相当于类,而i,j相当于对象,它们属于集合int里面的一个元素.
在CPP中定义一个类的模板如下:
class className
{
private:
memberData;
memberFunction;
public:
memberData;
memberFunction;
protected:
memberData;
memberFunction;
};
它把一些编程需要处理的属性(数据)及处理属性的行为(函数),打成一个包(类),并限定了其访问权限.一个良好的编程习惯是,把函数的声明放在类内,而函数的实现则放在类外.如下: <type> <class_name>::<func_name>(<args>)
{
Your Func Code...
}
在定义一个类时,有些地方是需要注意的.其最本质的原理是"类只是一个符号,它并不占用内存".这意味着定义一个类时不能涉及到内存存储的代码.如:
class Test
{
int i = 0;
int j = -1
};
一些对数据存储方式限定的关键字也是不能用在类内的,如auto,register.
一个类的示例代码:
#include <iostream>
class simpleClass
{
private:
float x,y;
public:
float m,n;
void setXY(float,float);
void getXY();
};
void simpleClass::setXY(float a,float b)
{
x = a;
y = b;
}
void simpleClass::getXY(void)
{
std:: cout << x << '\t' << y << std::endl;
}
int main(void)
{
simpleClass cls1;
cls1.m = 10;
cls1.n = 20;
cls1.setXY(2.0,5.0);
cls1.getXY();
return 0;
}
编译运行:
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# g++ example.cpp -o example
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# ./example
2 5
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program#