对象和类——类的真正形态

类的真正形态

在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
{
publicvoid peel()
     {
          printf("in peel\n");
     }
private:
     int weight;
}

//声明和实现分离
//头文件
class Fruit
{
publicvoid peel();

private:
     int weight;
}

//.cpp源文件
void Fruit::peel()
{
     printf("in peel\n");    
}

分析:
1. 第一种形式通常用于非常简短的函数,它的代码在编译时在声明处自动展开(相当于inline),这样在运行时就不必付出函数调用的代价。由于它会使编译后的代码变长,所以只适用于非常简短的函数。
2. 第二种形式更为常见,它的好处是可以通过使用头文件,使源代码的组织形式更为清晰。实现了将类的实现和定义分开
a) .h头文件中只有类的声明(成员变量和成员函数的声明)
b) .cpp源文件中完成类的其他实现(成员函数的具体实现)

这两种方法在语义上是等价的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值