2016-11-26 C++琐碎学习整理

本文介绍C++中class的基本使用方法,包括构造函数、成员函数、this指针的概念及其应用,并通过实例演示如何比较两个Box对象的体积大小。

初学Cpp,学习收获

  • 面向对象的实现方式——class 使用的时候用.xxx表示
  • public 无权限
  • private有权限
  • protected
  • this指针来访问自己的地址(所有对象都可以),在成员函数的内部,用来指向调用的对象
#include <iostream>

using namespace std;

class Box
{
   public:
      // 构造函数定义
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      int compare(Box box)
      {
         return this->Volume() > box.Volume();
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   if(Box1.compare(Box2))
   {
      cout << "Box2 is smaller than Box1" <<endl;
   }
   else
   {
      cout << "Box2 is equal to or larger than Box1" <<endl;
   }
   return 0;
}

PS:只有成员函数才有this指针,友元函数没有this的用法

  • 静态成员(static):无论创建多少个类的对象,静态成员都只有一个副本
    普通全局变量和静态变量的联系和区别
    地址都是一样的,而且都是存放在RAM之中
    但是他们的作用域不同,
    静态变量是源文件
    全局变量是整个程序
    计算机区别他们的方式:通过变量的 linkage (即能否被链接器识别)属性,internal linkage 的变量只能被本文件访问,而 external linkage 的变量可以被其他文件访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值