无法创建自定义类的实例

时间:2015-01-17 06:12:26

标签: c++ g++

我创建了Point和Vector类。我现在正试图实例化它们,但是g ++不喜欢指针以外的任何东西;我无法创建实际变量。这是我实际编译的唯一内容(除了定义公共X和Y变量的公共构造函数外,ATM,Point和Vector都是空的):

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

int main()
{
    Point* p = new typename Point::Point(3, 3);
    Vector* v = new typename Vector::Vector(2, -4);
    Point* p2 = new typename Point::Point(p->X - v->X, p->Y - v->Y);
    std::cout << "Point p:  (" << p->X << "," << p->Y << ")" << std::endl;
    std::cout << "Vector v: (" << v->X << "," << v->Y << ")" << std::endl;
    std::cout << "Point p2: (" << p2->X << "," << p2->Y << ")" << std::endl;

}

为什么我要创建指针而不是变量?

1 个答案:

答案 0 :(得分:0)

以下是没有指针(live demo)的方法:

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

int main()
{
    Point p(3, 3);
    Vector v(2, -4);
    Point p2(p.X - v.X, p.Y - v.Y);
    std::cout << "Point p:  (" << p.X << "," << p.Y << ")\n";
    std::cout << "Vector v: (" << v.X << "," << v.Y << ")\n";
    std::cout << "Point p2: (" << p2.X << "," << p2.Y << ")\n";
}

此外,您实际上可以通过定义operator<<为您的类型创建自定义输出格式化程序,只需打印(live demo):

std::ostream& operator<<(std::ostream& os, Point const& p)
{
    return os << '(' << p.X << ',' << p.Y << ')';
}

std::ostream& operator<<(std::ostream& os, Vector const& v)
{
    return os << '(' << v.X << ',' << v.Y << ')';
}

int main() {
    Point p(3, 3);
    Vector v(2, -4);
    Point p2(p.X - v.X, p.Y - v.Y);
    std::cout << "Point p:  " << p << '\n';
    std::cout << "Vector v: " << v << '\n';
    std::cout << "Point p2: " << p2 << '\n';
}