C++ 保存在两个cpp文件中函数,怎样声明才能互相调用?

主函数所在cpp:
#include "menu_1.cpp"
#include "menu_2.cpp"
void main(){
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
menu_1();
case '1':
menu_2();
}

menu_1()所在menu_1.cpp:
void menu_1(){
//其他操作
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
exit(0);
case '1':
menu_2();
}

menu_2()所在menu_2.cpp:
void menu_2(){
//其他操作
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
exit(0);
case '1':
menu_1();
}

由于作业需要,必须将menu_1和menu_2放在两个cpp文件中,但按我那样在主函数前声明的话,编译时会在menu_1.cpp中menu_2();那一行显示无法识别标识符menu_2(),哪位老虾帮帮忙,指点下该怎么声明?
编辑环境是VisualStudio2008


#include "menu_1.cpp"
#include "menu_2.cpp"
这两句换成
extern void menu_1();
extern void menu_2();

在menu_1.cpp开头加上extern void menu_2();
在menu_2.cpp开头加上extern void menu_1();

还有,你的代码中有语法错误

void main()
{
char choice;
do
{
choice=_getch();
}
while(choice!='0'&&choice!='1'); // 这里要加分号

switch(choice)
{ // switch后面要跟大括号
case '0':
menu_1();
break; // 这里要加break
case '1':
menu_2();
break;
default:;
}
}

main(), menu_1(),menu_2(),都是如此。

此外,不知道你的"menu_1.cpp""menu_2.cpp"是否包含了_getch,exit的头文件
要记得包含上
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-06-15
在menu_1.cpp:要声明#include "menu_2.cpp"
在menu_2.cpp:要声明#include "menu_1.cpp"

如提示头文件多次编译 加上#pragma once 就可以啦
第2个回答  2015-10-26

一下为一个简单的例子:

// file C.h
# ifndef _FOO_H_
# define _FOO_H_
 
extern void sayHello();
 
# endif // _FOO_H_
 
// file B.cpp
# include "C.h"
# include <iostream>
using namespace std;
void sayHello()
{
     // say your hello
}
 
// file A.cpp
# include "C.h"
 
int main()
{
    sayHello();
    return 0;
}

第3个回答  2010-06-15
#include "menu_1.cpp"
#include "menu_2.cpp"
void main(){
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
menu_1();
case '1':
menu_2();
}
/////////////////////////////////////////////////
menu_1()所在menu_1.cpp:

/*
*/
ifndef MENU_1
#define MWNU_1
#include<stdio.h>
#endef

/*
*/
void menu_1(){
//其他操作
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
exit(0);
case '1':
menu_2();
}

///////////////////////////////////
ifndef MENU_2
#define MWNU_2
#include<stdio.h>
#include<menu_1.cpp>
#endef

/*
*/
menu_2()所在menu_2.cpp:
void menu_2(){
//其他操作
char choice;
do{
choice=_getch();
}while(choice!='0'&&choice!='1')
switch(choice)
case '0':
exit(0);
case '1':
menu_1();
}
第4个回答  2010-06-15
void menu_1()
void main()

你写的没错 只是没有声明 在MIAN前面声明一下 就可以调用了!!
相似回答