用关键字声明外部局部变量? 我想知道为什么C++不能提供一个关键字来在调用函数中声明变量,调用函数的本地函数。 实际上,我需要继承一个vector类,并且我必须定义通常的操作: template <unsigned int N> class Vector { public: Vector(const std::array<float, N>& coords); Vector<N>& operator*=(float k); // others... protected: std::array<float, N> m_coords; }; class Vector3 : public Vector<3> { public: Vector3(float x = 0.f, float y = 0.f, float z = 0.f); // some specific operations like cross product } template <unsigned int N> Vector<N> operator*(float k, const Vector<N>& a) { Vector<N> res(a); res *= k; return res; } 模板 类向量 { 公众: 向量(常量std::数组和坐标); 向量和运算符*=(浮点k); //其他。。。 受保护的: std::阵列m_坐标; }; 类向量3:公共向量 { 公众: 向量3(浮点x=0.f,浮点y=0.f,浮点z=0.f); //一些特定的操作,如叉积 } 样板 向量运算符*(浮点k、常量向量和a) { 向量res(a); res*=k; 返回res; }

用关键字声明外部局部变量? 我想知道为什么C++不能提供一个关键字来在调用函数中声明变量,调用函数的本地函数。 实际上,我需要继承一个vector类,并且我必须定义通常的操作: template <unsigned int N> class Vector { public: Vector(const std::array<float, N>& coords); Vector<N>& operator*=(float k); // others... protected: std::array<float, N> m_coords; }; class Vector3 : public Vector<3> { public: Vector3(float x = 0.f, float y = 0.f, float z = 0.f); // some specific operations like cross product } template <unsigned int N> Vector<N> operator*(float k, const Vector<N>& a) { Vector<N> res(a); res *= k; return res; } 模板 类向量 { 公众: 向量(常量std::数组和坐标); 向量和运算符*=(浮点k); //其他。。。 受保护的: std::阵列m_坐标; }; 类向量3:公共向量 { 公众: 向量3(浮点x=0.f,浮点y=0.f,浮点z=0.f); //一些特定的操作,如叉积 } 样板 向量运算符*(浮点k、常量向量和a) { 向量res(a); res*=k; 返回res; },c++,inheritance,operator-overloading,external,keyword,C++,Inheritance,Operator Overloading,External,Keyword,如果我返回对新对象的引用,这样的函数将适用于每个继承的向量 template <unsigned int N> Vector<N>& operator*(float k, const Vector<N>& a) { Vector<N>* res = a.getClone();// virtual method returning a new object *res *= k; return &res;

如果我返回对新对象的引用,这样的函数将适用于每个继承的向量

template <unsigned int N>
Vector<N>& operator*(float k, const Vector<N>& a)
{
    Vector<N>* res = a.getClone();// virtual method returning a new object
    *res *= k;
    return &res;
}
模板
向量和运算符*(浮点k、常量向量和a)
{
Vector*res=a.getClone();//返回新对象的虚拟方法
*res*=k;
返回&res;
}
但是,我不想在调用函数中删除res,所以我想创建一个调用函数的局部变量


可能吗?

对不起,我忘记了外部函数的模板方法:

template <class T>
T operator*(float k, const T& a)
{
    T res(a);
    res *= k;
    return res;
}
模板
T运算符*(浮动k,常数T&a)
{
T res(a);
res*=k;
返回res;
}
因此,我可以使用Vector3操作我的隐藏向量方法


然而,我没有回答关键词问题。

@MohitJain这就是它的内在含义。我真的不明白这个问题
Vector操作符*(float k,const Vector&a){return k*a;}
应该做这项工作,不是吗?我想问的是,为什么首先要返回一个引用而不是一个值。您的代码本身没有什么意义。您声明返回一个引用,但实际上返回了一个指针(
return&res;
)。行
*res*=k意味着向量类型已经有一个操作符*(float);由于我上面给出的原因,您向我们展示的代码甚至不应该编译。