前言:
说实在的当我们接触到真正的C++开发时,比如说MFC的一个简单项目,我们会发现我们缺的不是基础知识,而是一种编码思维或者说模式,常常会出现一些我们看不懂的代码,其实这才是初学者正真缺少的一种‘编码感觉’,这是需要时间去磨练和感受的,书本上和别人的指导都帮不了你。
我现在要讲的是在我的一个MFC的Demo中出现了大量的define宏定义,我发现原来宏定义可以这样玩;
main.cpp
#include <iostream>
#include "student.h"
using namespace std;
struct Student {
string name;
int num;
Sex sex;
int age;
Student() {}
void toString() {
cout << " name = " << name << " num = " << num << " sex = " << sex << " age = " << age
<< endl;
}
}
#define NICE() Student()
#define MAX()\
new Student();
#define MAX_()\
public: \
virtual Student* getStudent(){\
Student* student= new Student();\
student->toString(); \
return student; \
};\
virtual void mAXShow()=0; \
#define BEGIN {
#define END }
#define CHECKZERO(divisor)\
if(divisor==0)\
printf("***ATTEMPT TO DIVIDE BY ZERO IN LINE %d of file %s ***\n",__LINE__,__FILE__);\
class A {
public:
string name;
A();
A(string &name) : name(name) {
}
virtual void out1()=0; /////纯虚函数 由子类实现
virtual ~A() {};
virtual void out2() ////虚函数 /默认实现
{
cout << "A(out2)" << endl;
}
virtual void out4()=0; ///普通类函数
void out3() ///普通类函数
{
cout << "A(out3)" << endl;
}
MAX_()
};
A::A() {
}
//void A::out4() {}
class B : public A {
public:
B(string &name) : A(name) {}
B();
virtual ~B() {};
void out1() {
cout << "B(out1)" << endl;
}
void out2() {
cout << "B(out2)" << endl;
}
void out3() {
cout << "B(out3)" << endl;
}
virtual void out4();
void mAXShow() {
cout << "B->mAXShow" << endl;
}
Student *getStudent() {
A::getStudent();
cout << "B->getStudent" << endl;
}
};
B::B() {
}
//注意void写法 在B::之前
void B::out4() {
}
调用:
A *ab = new B;
ab->getStudent();
Student *student = MAX();
student->toString();
NICE().toString();
BEGIN
CHECKZERO(0);
cout << "******BEGIN*********END*********" << endl;
END
输出:
name = num = 0 sex = 1989424688 age = 0
B->getStudent
name = num = 1835619112 sex = 1718185072 age = 694445417
name = num = 2686760 sex = 2686916 age = 1988922581
***ATTEMPT TO DIVIDE BY ZERO IN LINE 148 of file D:\WorkSpace_C\CaddMore\main.cpp ***
******BEGIN*********END*********
总结:
1.virtual void out4();不允许出现这样的写法,需要末尾加上‘=0’,
或者:自己实现void A::out4() {},但是这也失去了多态的意义。
又或者:B中申明:virtual void out4(); 在其外部实现:void B::out4(){}。
2.#define 可以简单的理解为对象中的‘include’方式。
3.”\”可以支持多行操作。
4.’#define BEGIN { ‘在后面的调用中纯粹起到替换作用,确实颠覆了java的三观。
5.重点,MAX_()综合了以上的写法,在他的实现类B中,mAXShow需要重写,
getStudent 在实现时 A::getStudent();起到调用A的getStudent方法作用,最后注意:A类中MAX_()的写法,只能被申明,不能出现在函数体内被调用,且不需要‘;’。这样恰好说明了#define的’include’作用。
ps:以上均属一个C++菜鸟的理解。