我认为友元函数可以访问类变量,就像我尝试在 << 函数中执行 vx、vy、vz 一样。但它不编译。它说它无法在这些行解析标识符。
我也在尝试学习如何使用命名空间。即使我在实现文件中使用了命名空间 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;
}
//Have also tried adding vec:: and Vector:: before operator<< here.
std::ostream& operator<<(std::ostream& out, const Vector& v) {
out<<"<"<<v.x<<", "<<v.y<<", "<<v.z<<">";
return out;
}