检查下错误

来源:百度知道 编辑:UC知道 时间:2024/05/16 21:18:19
用来试验子类是否会覆盖父类函数的程序,编译不过,查下
//1.h
#include <iostream>
using namespace std;
class a
{
public:
void out();
};
//1.cpp
#include "1.h"
#include <iostream>
using namespace std;

void a::out()
{
cout<<"a's out()";
}
//2.h
#include "1.h"

class b:public a
{
public:
void out();
};

//2.cpp
#include "2.h"

#include <iostream>
using namespace std;

void b::out()
{
cout<<"b's out";
}

//main.cpp
#include "2.h"
#include "1.h"
#include <iostream>
using namespace std;

void main()
{
a aa;
b bb;
aa.out();
bb.out();
aa.out();

}

我说下,

《main.cpp》 文件里
#include "2.h"
#include "1.h"
main.cpp包含2.h和1.h
因为2.h已经包含了1.h
所以在main.cpp里包含了2次1.h
造成重复定义。
你需要在.h里面用#ifudef #end这样的预编译来保证只定义一次。
像这样
#ifndef Unit1H
#define Unit1H
int i;
class a
{
}
.......
#endif

或者不那么麻烦的话,main.cpp文件只包含2.h一个文件就可以了