是否有任何常用的C++编译器允许这种语法

Are there any commonly used C++ compilers that would allow this syntax?

本文关键字:编译器 许这种 语法 C++ 任何常 是否      更新时间:2023-10-16

我是C++新手,并试图让这个开源程序(为/在 Linux 中开发(在 OS X 上的 xcode 中编译和运行。

当我编译并运行代码时,我收到很多错误(超过 xcode 愿意计算(,例如use of undeclared identifier 'x'use of undeclared identifier 'y'

下面是引发错误的代码示例:

template<typename T>
struct TVector2 {
    T x, y;
    TVector2(T _x = 0.0, T _y = 0.0)
        : x(_x), y(_y)
    {}
    double Length() const {
        return sqrt(static_cast<double>(x*x + y*y));
    }
    double Norm();
    TVector2<T>& operator*=(T f) {
        x *= f;
        y *= f;
        return *this;
    }
    TVector2<T>& operator+=(const TVector2<T>& v) {
        x += v.x;
        y += v.y;
        return *this;
    }
    TVector2<T>& operator-=(const TVector2<T>& v) {
        x -= v.x;
        y -= v.y;
        return *this;
    }
};
struct TVector3 : public TVector2<T> {
    T z;
    TVector3(T _x = 0.0, T _y = 0.0, T _z = 0.0)
    : TVector2<T>(_x, _y), z(_z)
    {}
    double Length() const {
        return sqrt(static_cast<double>(x*x + y*y + z*z)); //use of undeclared identifier x
    }
    double Norm();
    TVector3<T>& operator*=(T f) {
        x *= f;
        y *= f;
        z *= f;
        return *this;
    }

在我看来,作为一个没有经验的C++程序员,看起来x和y只是未声明的局部变量。我可以通过简单地声明变量来让编译器摆脱错误,就像这样......

struct TVector3 : public TVector2<T> {
    T z;
    T x;
    T y;

然而,这些错误的绝对数量让我认为

  1. 可能有(相当常见的(C++编译器版本允许您将变量 x 声明为 _x。这可以解释为什么我下载的源代码有这么多编译器错误。
  2. 也许我得到了一个"坏批次"的源代码,我不应该浪费时间让它编译,因为源代码以某种方式很糟糕。

有经验的C++开发人员可以解释一下可能发生的事情吗?

  • xy 是基类 TVector2<T> 的数据成员。

  • 因为基类是依赖于模板参数T的类型,所以在查找非限定名时不会搜索基类。

  • 我相信 MSVC 曾经编译过这段代码,不确定它是否仍然在 C++11 模式下。原因是 MSVC 没有在模板中正确执行名称解析。

  • 解决方法通常是说this->x而不是x