Before we start designing the Crest, let's take a look at the code.
Using System;
Using System. Collections. Generic;
Public abstract class Bird {
Protected String name;
Public abstract String tweet ();
Public String getName () {return name ;}
}
Public class Cock: Bird {
Public override String tweet () {return "woooooo ";}
Public virtual String walk () {return "cock walk ";}
Public void setName (String newName) {name = newName ;}
}
Public class MainClass
{
Public static void Main ()
{
Bird bird = new Cock ();
Cock cock = new Cock ();
System. Console. WriteLine (bird. tweet ());
}
}
This is a piece of pure object-oriented code, and our topic will follow this piece of code. First, we design Crest to support the simplest objects.
Simple Object
Because of the limitations of C language, we need to simulate a class definition that can only use struct. The simplest class is of course an empty class. Our C code is as follows:
Struct CEmptyObject
{
}
Then we need to add our CEmptyObject class to the member variable, which is also very simple:
Struct CEmptyObject
{
Int salary;
};
Add another member function. I want to add a getSalary, but the question is, how can I add it? Write the following statement:
Int getSalary () {return salary ;}
It seems correct, but the C compiler report salary cannot find it. If you put this line of code in struct CEmptyObject, it is also a compilation Error [BCC32 Error] raw. c (143): E2200 Functions may not be part of a struct or union. In fact, the implementation of most OO languages is similar, so we will not sell off the customs. We will copy them as follows:
Int getSalary (struct CEmptyObject * _ this)
{
Return _ this-> salary;
}
All code similar to xxx. getSalary () written in our code is actually converted into the getSalary (xxx) form. If you are familiar with the C # Extension function, you can better understand this.
Use of Simple objects
We have designed a simple object. Of course we need to use it. Let's take a look at it first.