【问题标题】:C++ class definition compile problemsC++类定义编译问题
【发布时间】:2011-02-27 01:22:55
【问题描述】:

我已经翻遍了,我找不到任何与我的问题有关的东西。我试图为一个多边形类编写一个类定义,该类基本上具有一个包含指向一个点的指针的向量。当我尝试编译时,我不断收到以下错误...

错误 C2143:语法错误:缺少 ';'在'

这是类的代码

#include "Point.h"
#include <vector>

class Point;

class Polygon
{
private:
    vector<Point*> myPolygonPoints;
    bool myHasIntersection;

public:
    void addSetOfPoints(vector<Point*> points)
    {
        myPolygonPoints = points;
    }

    bool getHasIntersection()
    {
        return myHasIntersection;
    }

    void setHasIntersection(bool intersection)
    {
        myHasInstersection = intersection;
    }

};

【问题讨论】:

  • 风格说明:最好先显示public 部分,然后是protected,最后是private 部分。该类的用户只对第一个感兴趣(在继承的情况下可能是第二个),并且不太关心 private 一个,因此无需将其放在她的视线中。
  • 我不能为别人说话,但我总是有兴趣看到私人细节。

标签: c++ templates compiler-errors


【解决方案1】:

您正在使用来自std 命名空间的vector,但未对其进行限定。

您要么必须执行 using namespace std; 或 using std::vector,要么使用 std 命名空间(如 std::vector)声明所有 vector 对象。

#include "Point.h"
#include <vector>

class Point; // Assuming Point.h has this declared,
             // you don't need this forward declaration, but in reality,
             // you don't need to include Point.h
             // since you're only declaring pointers to Points

class Polygon
{
private:
    std::vector<Point*> myPolygonPoints;
    bool myHasIntersection;

public:
    void addSetOfPoints(std::vector<Point*> points)
    {
        myPolygonPoints = points;
    }

    bool getHasIntersection()
    {
        return myHasIntersection;
    }

    void setHasIntersection(bool intersection)
    {
        myHasInstersection = intersection;
    }

};

【讨论】:

    【解决方案2】:

    vector 在 std:: 命名空间中。所以你的示例代码中未定义向量

    两种可能的解决方案:

    #include <vector>
    using std::vector;
    

    或:(在所有情况下通过引用向量的代码,包括声明和引用)

    private:
      std::vector<Point*> myPolygonPoints;
    public:
      void addSetOfPoints(std::vector<Point*> points)
    

    等等


    第三种解决方案如下:

    #include <vector>
    using namespace std;
    

    最后一个,从编码风格的角度来看,我觉得不太受欢迎。原因是它将 std 命名空间中的所有内容都导入到默认命名空间中。相比之下,我发现显式导入我正在使用的部分更可取,因为它可以让我跟踪我需要标题的原因。在这种情况下这没有意义(当然我需要&lt;Vector&gt;,我使用的是std::vectors)。在这样的情况下,它更相关:

    #include <algorithm>
    using std::adjacent_find;
    

    哦,是的,这就是为什么我把它包括在内......

    【讨论】:

    • 感谢所有解决问题的人。
    【解决方案3】:

    如果你没有明确声明你正在使用 std 命名空间,你应该引用哪个命名空间向量属于。

    【讨论】:

      【解决方案4】:

      除了std::vector 的问题,您还在setHasIntersection 方法中拼错了myHasIntersection 变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-20
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-28
        • 1970-01-01
        相关资源
        最近更新 更多