【发布时间】:2022-01-16 21:12:23
【问题描述】:
我可以用头文件中的其他语法替换实现文件中的using namespace std; 吗?包含此代码以使cout 正常工作的最佳方法是什么?
这是我的头文件:
#ifndef LINE_H
#define LINE_H
#include<iostream>
#include<cmath>
class Line
{
public:
Line();
Line(double x1, double y1, double x2, double y2);
void setLine(double a1, double b1, double a2, double b2);
double getLen();
void printLine();
~Line();
private:
double x1,y1,x2,y2,length;
double Length(double a1, double b1, double a2,double b2);
};
#endif // LINE_H
这是实现文件:
#include "Line.h"
using namespace std;
// **********Constructors*****************
Line::Line() {}
Line::Line(double x1, double y1, double x2, double y2){
this-> x1=x1; this-> y1=y1; this->x2=x2; this->y2=y2;
length = Length(x1,y1,x2,y2);
}
// ***********Public Methods***********************
void Line::setLine(double a1, double b1, double a2, double b2){
x1=a1; y1=b1; x2=a2; y2=b2;
length = Length(x1,y1,x2,y2);
}
double Line::getLen(){
return length;
}
void Line::printLine(){
cout<<"("<<x1<<","<<y1<<") --> ("<<x2<<","<<y2<<")"<<endl;
}
// ***********Private Methods***************
double Length(double a1, double b1, double a2,double b2){ //Private method which calculates the distance between 2 points.
return sqrt(pow(b2-b1,2)+pow(a2-a1,2));
}
// ***********Destructor******************
Line::~Line(){}
【问题讨论】:
-
double Length(必须是double Line::Length(。 -
@DanielLangr 谢谢。关于另一个问题 - 包含“使用命名空间”的可接受方式是什么?在头文件中?在实现文件中?
-
永远不要在文件/公共命名空间范围的头文件中使用
using指令。有关详细信息,请参阅stackoverflow.com/questions/1452721/…、stackoverflow.com/questions/5849457/… 等。通常,using namespace ...本身通常是不好的做法。 -
没有可接受的方式来包含(或以其他方式使用)
using namespace。它是一种反模式;只是避免它。在源/定义文件的最里面(理想情况下是匿名的)namespace中使用不带namespace的using声明,如果绝对必要,在头文件中使用private:作为快捷方式引入的成员类型和using。永远不要使用整个命名空间;它违背了命名空间的目的。 -
最好的方法是每次引用
std::cout时都拼出完全限定的名称。