用关键字声明外部本地变量

Declare an external local variable with a keyword?

本文关键字:变量 外部 关键字 声明      更新时间:2023-10-16

我想理解为什么C 不能提供一个关键字来声明称为函数的变量,该函数本地为呼叫函数。实际上,我需要继承一个向量类,并且必须定义通常的操作:

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;
}

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

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;
}

但是,我不想在调用函数中删除res,所以我想创建一个呼叫函数的局部变量。

可能?

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

template <class T>
T operator*(float k, const T& a)
{
    T res(a);
    res *= k;
    return res;
}

因此,我可以用vector3。

我没有回答关键字问题。