Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

5-Use pointer or class to declare object #6

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

創建Object有兩種方法

#include <iostream>
using namespace std;

class Student{
};

int main()
{
    Student Amy;
    Student *Jim = new Student;
}

1.使用class直接宣告物件

Student Amy;

2.使用pointer去nwe一個新的物件

Student *Jim = new Student; 

使用class直接宣告物件

當創立class Student時,會自動創立Student 這個最基本的constructor

class Student{
public:
    Student(){
    }
};

Student Amy; 會自動轉成 Student Amy = Student(); 其運作真實狀況如下:

class Student{
public:
    Student(){
    }
};

int main()
{
    Student Amy = Student();
}

此時主要的特性如下

使用pointer去nwe一個新的物件


class Student{
};

int main()
{
    Student *Jim = new Student;
}

Always prefer the alternatives unless you really need pointers.

通常以下狀況才需要使用pointer去宣告物件

  1. You need reference semantics.
  2. You need polymorphism.
  3. You want to represent that an object is optional
  4. You want to decouple compilation units to improve compilation time.
  5. You need to interface with a C library

class Student{};
class ChemsitryStudent : public Student{};

int main()
{
    Student *Amy = new Student;
    Student *Bob = new ChemsitryStudent;
    ChemsitryStudent *Cindy = new Student; // >>error
    ChemsitryStudent *David = new ChemsitryStudent;
}

只有 ChemsitryStudent *Cindy = new Student; 會產生error

Student *Bob = new ChemsitryStudent;此時Bob的型態為Student物件,不是ChemsitryStudent物件

#include <iostream>
using namespace std;

class Student{
public:
    void Hello(){
        cout << "I'm a student.\n";
    }
};

class ChemsitryStudent : public Student{
public:
    void Hello(){
        cout << "I'm a student major in chemistry.\n";
    }

    void DoResearch(){
        cout << "I'm doing research.\n";
    }    
};

int main()
{
    Student *Bob = new ChemsitryStudent;
    Bob->Hello();
    // Bob->DoResearch(); >>error

    ChemsitryStudent *David = new ChemsitryStudent;
    David->Hello();
    David->DoResearch();
}

output

I'm a student.
I'm a student major in chemistry.
I'm doing research.

使用指針去存取object

#include <iostream>
using namespace std;

class Student{
public:

    void Hello(){
        cout << "I'm a student.\n";
    }
};

class ChemsitryStudent : public Student{
public:
    void Hello(){
        cout << "I'm a student major in chemistry.\n";
    }

int main()
{
    ChemsitryStudent Amy;

    Student* p1 = &Amy;
    p1->Hello();

    ChemsitryStudent* p2 = &Amy;
    p2->Hello();
}

output

I'm a student.
I'm a student major in chemistry.