C++沉思录笔记 —— 序幕

#include <stdio.h>
 
class Trace{
public:
  void print(const char* s) { printf("%s\n", s); }
};

int main(int argc, char const *argv[])
{
  Trace t; t.print("begin main()");
  //do something
  t.print("end main()"); return 0;
}

第一段代码:

这里有两个概念需要了解 —— 类 和 类的对象。Trace是一个类, t 是 Trace 类的对象。

类的成员包括 数据 和 方法。

方法属于类,数据属于类对象。—— 理解它。在你的脑海里有具体的图像。你要知道这句话在说什么。

举例说:

Trace 类 可以创建无数个对象,每个对象的方法都是类的方法,方法的入口(函数地址)是类的,不会因为对象不同而不同。

Trace 类 可以创建无数个对象,每个对象的数据都是对象的数据,每个对象的数据的存储空间和其他的对象的数据的存储空间不一样。

class Trace{
public:
  Trace() { noisy = 0; }
  void print(const char* s) { if(noisy) printf("%s\n", s); }
  void on() { noisy = 1; }
  void off() { noisy = 0; }
private:
  int noisy;
};

第二段代码:

Trace t1; t1.noisy = 0;

Trace t2; t2.noisy = 1;

创建了两个Trace类对象, t1 和 t2。

有了类的对象,数据才具体,数据是属于对象的。换句话说对象就是因为被赋予了数据,才从类这个抽象的概念中脱离出来,成了具体的存在。

当类的对象被创建时,同时就有了this指针(这是个非常关键的隐藏属性)。this指针在计算机里的实现方式是对象数据的起始地址。

因为对象数据的存储地址独一无二,所以每个对象的this指针也是独一无二的。

t1.print("Hello");

t2.print("Hello");

其实print方法有两个参数。

 void print(const char* s) { printf("%s\n", s); } 相当于 void print(Trace * const this,const char* s) { printf("%s\n", s); }

const 在 * 右边表示 指针地址(this)是常量,const在 * 左边表示 指针(s)指向的内容是常量。

#include <stdio.h>
 
class Trace{
public:
    Trace() { noisy = 0; f = stdout; }
    Trace(FILE* ff) { noisy = 0; f = ff; }
    void print(const char* s) { if(noisy) fprintf(f, "%s\n", s); }
    void on() { noisy = 1; }
    void off() { noisy = 0; }
private:
    int noisy;
    FILE* f;
};
 
int main(int argc, char const *argv[])
{
    Trace t(stderr);

    t.print("begin main()");
    //do something
    t.print("end main()");

    return 0;
}

 第三段代码:

修改Trace类,可以任意指定输出文件,而且不影响之前写的程序的正常工作。

C++ 类的特殊方式的使用可以让改进程序变得轻而易举。

猜你喜欢

转载自www.cnblogs.com/vonyoven/p/11771099.html