![](/img/trans.png)
[英]Why can't a friend function access the private variables of an inherited class?
[英]Friend function can't access class variables
我认为朋友函数可以访问类变量,就像我在<<函数中尝试执行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;
}
//Operators
std::ostream& operator<<(std::ostream& out, const Vector& v) {
out<<"<"<<v.x<<", "<<v.y<<", "<<v.z<<">";
return out;
}
Friend函数不是成员函数, operator<<
不必是成员,以便具有ostream
的左侧。 将其更改为自由功能:
std::ostream& operator<<(std::ostream& out, Vector v) {
^^ no qualification
我也将通过const引用而不是按值来获取向量。
您的朋友函数属于名称空间vec,因此必须定义为此类。
更改为:
std::ostream &vec::operator << (std::ostream &out , const Vector &v) { //etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.