访问类的元素

时间:2014-01-31 01:26:38

标签: c++ class vector

我正在尝试创建一个类'delta',表示为'vertex'类型的向量,'vertex'是由'x'和'y'组成的结构,它们是double类型。我需要在'triangle'中有一个使用herons公式返回区域的成员函数,但我无法弄清楚如何访问三角形中每个元素的单独x和y分量。到目前为止,这是我的代码,麻烦来自第三段代码 - triangle.cpp文件

vertex.h:

#ifndef VERTEX_H
#define VERTEX_H

#include <iostream>

struct vertex
{
    double x, y;

    vertex(double ix = 0.0, double iy = 0.0)
    {
        x = ix;
        y = iy;
    }
};

#endif // VERTEX_H

triangle.h:

#ifndef TRIANGLE_H
#define TRIANGLE_H

#include <iostream>
#include <vector>
#include "vertex.h"

class triangle
{
public:
    triangle(vertex iv0 = vertex(), vertex iv1 = vertex(), vertex iv2 = vertex());
    // pre:
    // post: empty triangle

    triangle(const triangle & source);
    // pre:
    // post: triangle created and initialized to given triangle source

    vertex operator[](size_t i) const;
    // pre: 0 <= i < 3
    // post: return vertex i in this triangle

    double area() const;
    //pre:
    //post: returns area of triangle

private:
    std::vector<vertex> v;
};

std::ostream & operator << (std::ostream & os, const triangle & t);
std::istream & operator >> (std::istream & is, triangle & t);
#endif // TRIANGLE_H

triangle.cpp源文件:

#include <cassert>
#include <vector>
#include <cmath>
#include "triangle.h"

triangle::triangle(vertex iv0, vertex iv1, vertex iv2)
{
    v = std::vector<vertex> ();
    v[0] = iv0;
    v[1] = iv1;
    v[2] = iv2;
}

triangle::triangle(const triangle &source)
{
    v = source.v;
}

vertex triangle::operator[] (std::size_t i) const
{
    assert(i < v.size());
    return v[i];
}
 //HERE IS THE PROBLEM
double triangle::area() const
{
    int a, b, c;
    double s;
    //need to use something like a = (v[0].y-v[1].y)/(v[0].x-v[1].x) to calculate area,
    //   this syntax is wrong however^^^
    s = (a+b+c)/2;
    return sqrt(s*(s-a)*(s-b)*(s-c));
}

std::ostream & operator << (std::ostream & os, const triangle & t)
{
    for (size_t i = 0; i < 3; ++i)
        os << t[i] << " ";
    return os;
}

std::istream & operator >> (std::istream & is, triangle & t)
{
    std::size_t n;
    vertex vx;

    is >> n;
    for (size_t i = 0; i < n; ++i)
    {
        is >> vx.x >> vx.y;
    }
    return is;
}

1 个答案:

答案 0 :(得分:2)

访问向量的方式没有任何问题(v[0].x 是正确的),但是如何初始化它有一个问题:

triangle::triangle(vertex iv0, vertex iv1, vertex iv2)
{
    v = std::vector<vertex> ();
    v[0] = iv0;
    v[1] = iv1;
    v[2] = iv2;
}

矢量大小为零。你不能只把物品推到它上面。使用push_back成员,或明确设置大小。事实上,使用矢量是值得怀疑的。三角形不需要任意数量的顶点。它完全需要3.阵列就可以了。

以下是我提到的两个基于矢量的选项:

// Using push_back
triangle::triangle(vertex iv0, vertex iv1, vertex iv2)
{
    v.reserve(3);
    v.push_back(iv0);
    v.push_back(iv1);
    v.push_back(iv2);
}

// Preallocating a vector size before modifying elements
triangle::triangle(vertex iv0, vertex iv1, vertex iv2)
    : v(3)
{
    v[0] = iv0;
    v[1] = iv1;
    v[2] = iv2;
}