C++ 是否访问类/结构范围之外的受保护成员?

C++ 是否访问类/结构范围之外的受保护成员?,c++,templates,struct,operator-overloading,protected,C++,Templates,Struct,Operator Overloading,Protected,我有一堆模板结构(Vec3,Vec4,Mat4,…),我正在进行大量的运算符重载。我将Mat4*Vec4定义为通常的矩阵向量乘法。现在我想将Vec4*Mat4定义为逐行乘法 为了访问受保护的数据字段,我还对底层数据结构(我正在使用SIMD向量)进行了保护,并将结构设置为friends 问题是我想在Mat4头文件中定义operator*(const Vec4&,const Mat4&)。通常我定义交换算子的方法是: template<typename T> Vec3<T>

我有一堆模板结构(
Vec3
Vec4
Mat4
,…),我正在进行大量的运算符重载。我将
Mat4*Vec4
定义为通常的矩阵向量乘法。现在我想将
Vec4*Mat4
定义为逐行乘法

为了访问受保护的
数据
字段,我还对底层数据结构(我正在使用SIMD向量)进行了保护,并将结构设置为friends

问题是我想在
Mat4
头文件中定义
operator*(const Vec4&,const Mat4&)
。通常我定义交换算子的方法是:

template<typename T>
Vec3<T> operator*(const T & s, const Vec3<T> & v)
{
    return v * s;
}
有没有办法“让函数成为结构的朋友”

是的,您可以将Functionoin模板的专门化声明为
friend
。e、 g

// forward declaration
template<typename T>
class Vec4;
template<typename T>
class Mat4;

// declaration
template<typename T>
Vec4<T> operator*(const Vec4<T>&, const Mat4<T>&);

template<typename T>
class Vec4 {  
    // friend declaration  
    friend Vec4<T> operator* <T> (const Vec4<T>&, const Mat4<T>&);
    ...
};

template<typename T>
class Mat4 {    
    // friend declaration  
    friend Vec4<T> operator* <T> (const Vec4<T>&, const Mat4<T>&);
    ...
};

// definition  
template<typename T>
Vec4<T> operator*(const Vec4<T>&, const Mat4<T>&)
{
    ...
}
//转发声明
模板
Vec4类;
模板
Mat4类;
//声明
模板
Vec4运算符*(常数Vec4&,常数Mat4&);
模板
类Vec4{
//朋友宣言
友元Vec4运算符*(常数Vec4&,常数Mat4&);
...
};
模板
类Mat4{
//朋友宣言
友元Vec4运算符*(常数Vec4&,常数Mat4&);
...
};
//定义
模板
Vec4运算符*(常数Vec4&,常数Mat4&)
{
...
}

在这个问题上,你有没有把
+
*
搞混了?@NeilGatenby是的,对不起。修复了将相同的
Mat4运算符*(const Vec4&,const Mat4&)声明为两个结构的朋友函数的问题?
// forward declaration
template<typename T>
class Vec4;
template<typename T>
class Mat4;

// declaration
template<typename T>
Vec4<T> operator*(const Vec4<T>&, const Mat4<T>&);

template<typename T>
class Vec4 {  
    // friend declaration  
    friend Vec4<T> operator* <T> (const Vec4<T>&, const Mat4<T>&);
    ...
};

template<typename T>
class Mat4 {    
    // friend declaration  
    friend Vec4<T> operator* <T> (const Vec4<T>&, const Mat4<T>&);
    ...
};

// definition  
template<typename T>
Vec4<T> operator*(const Vec4<T>&, const Mat4<T>&)
{
    ...
}