这个C++问题求解答
main函数文件里:#include<iostream>#include"complex.h"usingnamespacestd;intmain(){complexc1(...
main函数文件里:
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
complex c1(1,2);
complex c2(3,4);
double r=3;
fufu(c1,c2);
fushi(r,c1);
fushi(r,c2);
return 0;
}
complex类文件里:
#ifndef COMPLEX_H
#define COMPLEX_H
class complex
{
public:
complex(double reall,double imgl);
friend void fufu(complex &a,complex &b);
friend void fushi(double r,complex &p);
private:
double real,img;
};
#endif
complex.cpp文件里:
#include "complex.h"
complex::complex(double reall,double imgl)
{real=reall;
img=imgl;
}
void fufu(complex &a,complex &b)
{
cout<<"复数与复数相加后结果为:"<<a.real+b.real<<"+"<<a.img+b.img<<"i"<<endl;
cout<<"复数与复数相减后结果为:"<<a.real-b.real<<"+"<<a.img-b.img<<"i"<<endl;
}
void fushi(double r,complex &p)
{cout<<"复数与实数相加后结果为"<<p.real+r<<"+"<<p.img<<"i"<<endl;
cout<<"复数与实数相减后结果为:"<<p.real-r<<"+"<<p.img<<"i"<<endl;
}
为什么运行中显示complex.cpp文件里的cout和endl未被声明?
[Error] 'cout' was not declared in this scope
[Error] 'endl' was not declared in this scope 展开
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
complex c1(1,2);
complex c2(3,4);
double r=3;
fufu(c1,c2);
fushi(r,c1);
fushi(r,c2);
return 0;
}
complex类文件里:
#ifndef COMPLEX_H
#define COMPLEX_H
class complex
{
public:
complex(double reall,double imgl);
friend void fufu(complex &a,complex &b);
friend void fushi(double r,complex &p);
private:
double real,img;
};
#endif
complex.cpp文件里:
#include "complex.h"
complex::complex(double reall,double imgl)
{real=reall;
img=imgl;
}
void fufu(complex &a,complex &b)
{
cout<<"复数与复数相加后结果为:"<<a.real+b.real<<"+"<<a.img+b.img<<"i"<<endl;
cout<<"复数与复数相减后结果为:"<<a.real-b.real<<"+"<<a.img-b.img<<"i"<<endl;
}
void fushi(double r,complex &p)
{cout<<"复数与实数相加后结果为"<<p.real+r<<"+"<<p.img<<"i"<<endl;
cout<<"复数与实数相减后结果为:"<<p.real-r<<"+"<<p.img<<"i"<<endl;
}
为什么运行中显示complex.cpp文件里的cout和endl未被声明?
[Error] 'cout' was not declared in this scope
[Error] 'endl' was not declared in this scope 展开
展开全部
程序的问题是iostream使用的地方不对。类中使用到了cout和endl,而main函数未使用。因此应在类中引入iostream,而非在main函数中引入。
这个问题的核心御饥是,iostream要在用到它的地方引入。main函数中并未用到cout和endl等iostream中的对象,所以没必要在main函数中引入iostream。
另外,如果是在镇穗返类的定义中使用cout等std命名空间的对象,最好不要用using namespace std这种全局引入方式,以免对引入类的文件产生命名空间对象名冲突。可以使用using std::cout方式仅引入cout对象。
推荐的修改方案如下:
可以去掉main函数文件语句(main函数未用到iostream):
#include <iostream>
using namespace std;
在complex.cpp文件中加入语句族旦(仅引入std命名空间下的cout和endl对象):
#include <iostream>
using std::cout;
using std::endl;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询