我认为朋友函数可以访问类变量,就像我在如何尝试在函数中执行v.x,v.y,v.z一样。但它不编译。它说它无法解决这些线路上的标识符。朋友函数无法访问类变量
另外我想了解如何使用命名空间。即使我在实现文件中使用命名空间vec,我仍然必须在所有内容中包含Vector ::所以有什么意义?
头文件:
#ifndef VECTOR_H
#define VECTOR_H
namespace vec {
class Vector {
private:
double x, y, z;
public:
Vector(double, double, double);
friend std::ostream& operator<<(std::ostream&, const Vector&);
};
}
#endif /* VECTOR_H */
cpp文件:
#include "Vector.h"
#include <iostream>
using namespace vec;
//Constructor
Vector::Vector(double x1 = 0, double y1 = 0, double z1 = 0) {
x = x1;
y = y1;
z = z1;
}
//Operators
std::ostream& operator<<(std::ostream& out, const Vector& v) {
out<<"<"<<v.x<<", "<<v.y<<", "<<v.z<<">";
return out;
}
你的函数定义为'矢量::运算<<';它应该是'operator <<'... – 2013-02-12 00:02:07