gpt4 book ai didi

c++ - 具有成员运算符*的模板化运算符*的友元声明

转载 作者:行者123 更新时间:2023-11-30 04:09:27 28 4
gpt4 key购买 nike

附加到这个问题的代码无法编译 (g++ 4.7) 并出现以下错误:

test.cpp:22:31: error: declaration of ‘operator*’ as non-function
test.cpp:22:31: error: expected ‘;’ at end of member declaration
test.cpp:22:32: error: expected unqualified-id before ‘<’ token
test.cpp: In function ‘int main(int, char**)’:
test.cpp:39:11: warning: unused variable ‘d’ [-Wunused-variable]
test.cpp: In instantiation of ‘Vector3<T> operator*(T, const Vector3<T>&) [with T = float]’:
test.cpp:37:16: required from here
test.cpp:25:10: error: ‘float Vector3<float>::v [3]’ is private
test.cpp:30:57: error: within this context
test.cpp:25:10: error: ‘float Vector3<float>::v [3]’ is private
test.cpp:30:57: error: within this context
test.cpp:25:10: error: ‘float Vector3<float>::v [3]’ is private
test.cpp:30:57: error: within this context

但是,如果将友元声明移动到operator* 成员声明/定义之前(只需交换示例代码中的注释),那么它可以正常编译。我不明白为什么。有什么方法可以使这段代码与位于 operator* 成员声明之后的友元声明一起编译?

template<typename T>
class Vector3;

template<typename T>
Vector3<T> operator*(T f, const Vector3<T>& v);

template<typename T>
class Vector3 {
public:
Vector3(T x, T y, T z) {
v[0] = x;
v[1] = y;
v[2] = z;
}

//friend Vector3<T> operator*<>(T f, const Vector3<T>& v); // WORKS

T operator*(const Vector3<T>& other) const {
return (v[0] * other.v[0] + v[1] * other.v[1] + v[2] * other.v[2]);
}

friend Vector3<T> operator*<>(T f, const Vector3<T>& v); // FAILS

private:
T v[3];
};

template<typename T>
Vector3<T> operator*(T f, const Vector3<T>& v) {
return Vector3<T>(f * v.v[0], f * v.v[1], f * v.v[2]);
}

int main(int argc, char *argv[]) {
Vector3<float> v(0, 0, 0);
Vector3<float> w(0, 0, 0);

w = 2.0f * v;

float d = v * w;

return 0;
}

最佳答案

问题是您没有指定您的意思是来自全局命名空间的 operator*,要做到这一点,请将您的友元声明更改为:

friend Vector3<T> (::operator*<>)(T f, const Vector3<T>& v);

当您在 operator* 成员之前声明它时,没有歧义,因此它被正确拾取。

关于c++ - 具有成员运算符*的模板化运算符*的友元声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21221437/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com