类的真正形态
在C语言中,类是由struct关键字定义的,而在C++中是由class关键字定义的。那么这两者有什么不同呢?
类的关键字
1. struct在C语言中已经有了自己的含义,必须继续兼容
2. 在C++中提供了新的关键字class用于类定义
3. class和struct的用法是完全相同的。
示例代码:class初探
#include <stdio.h>
struct A
{
// defualt to public
int i;
// defualt to public
int getI()
{
return i;
}
};
class B
{
// defualt to private
int i;
// defualt to private
int getI()
{
return i;
}
};
int main()
{
A a;
B b;
a.i = 4;
printf("a.getI() = %d\n", a.getI());
b.i = 4;
printf("b.getI() = %d\n", b.getI());
return 0;
}
输出结果:
test.cpp: In function ‘int main()’:
test.cpp:17: error: ‘int B::i’ is private
test.cpp:34: error: within this context
test.cpp:19: error: ‘int B::getI()’ is private
test.cpp:36: error: within this context
分析:
1. 在用struct定义类时,所有成员的默认访问级别为public
2. 在用class定义类时,所有成员的默认访问级别为private
类的实现方式
示例代码:类的实现方式
//声明和实现一起
class Fruit
{
public:
void peel()
{
printf("in peel\n");
}
private:
int weight;
}
//声明和实现分离
//头文件
class Fruit
{
public:
void peel();
private:
int weight;
}
//.cpp源文件
void Fruit::peel()
{
printf("in peel\n");
}
分析:
1. 第一种形式通常用于非常简短的函数,它的代码在编译时在声明处自动展开(相当于inline),这样在运行时就不必付出函数调用的代价。由于它会使编译后的代码变长,所以只适用于非常简短的函数。
2. 第二种形式更为常见,它的好处是可以通过使用头文件,使源代码的组织形式更为清晰。实现了将类的实现和定义分开。
a) .h头文件中只有类的声明(成员变量和成员函数的声明)
b) .cpp源文件中完成类的其他实现(成员函数的具体实现)
这两种方法在语义上是等价的。