C++程序到C程序的翻译

  1. class CCar {
  2. public:
  3. int price;
  4. void SetPrice(int p);
  5. };
  6. void CCar::SetPrice(int p) {price = p}
  7. main() {
  8. CCar car;
  9. car.SetPrice(2000);
  10. }

最初没有C++编译器,所以要把C++程序翻译成C程序执行。上面的程序会被翻译如下:

  1. struct CCar {
  2. int price;
  3. };
  4. void SetPrice(struct CCar* this, int p) {
  5. this->price = p;
  6. }
  7. main() {
  8. struct CCar car;
  9. SetPrice( &car, 2000);
  10. }
  • But!
    1. claas A {
    2. int i;
    3. public:
    4. void Hello() {cout << "hello" << endl;}
    5. }; ——> void Hello(A * this){ cout << "hello" << endl; }
    6. main() {
    7. A * p = NULL;
    8. p->Hello(); ——> Hello(p); // 不会出错
    9. } // 输出:hello