C-language implementation of classes in C + +

Source: Internet
Author: User
Tags define function

The second interview question: C language How to implement classes in C + +

#include <stdio.h>
//C languages do not have classes, but you can use a struct as a class
//Unlike classes, structs can only define variables, cannot define functions, and can implement their functions 
//define "classes" by means of function pointers. The member variable and the method 
typedef struct person{
	char name;
	int age;
	void (*eatfunction) (struct person this, int num);
} person; 

define function 
void eatfunction (struct person this, int num) {
	printf ("test\n");
} 

The constructor for the definition "class"
//is different from the object-oriented, the C language "class" constructor cannot be placed in "class", can only be placed outside of "class"
//constructor primarily completes the initialization of the variable, and the assignment person of the function pointer 
* Newperson (person *this) {
	this->name = ' A ';
	This->age =;
	This->eatfunction = eatfunction;
} 

The main function calls 
int main () {person person
	;
	Newperson (&person);
	Person. Eatfunction (person,0);
	return 0;

Note: When testing to save in. c format, the. cpp format runs the error, because this is the keyword in C + +.

Reference Blog: http://dongxicheng.org/cpp/ooc/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.