无法创建自定义实例 class

Cannot create instance of custom class

我创建了 类 点和矢量。我现在正在尝试实例化它们,但是 g++ 除了指针之外什么都不喜欢;我无法创建实际变量。这是我实际编译的唯一东西(ATM、Point 和 Vector 是空的,除了定义 public X 和 Y 变量的 public 构造函数):

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

}

为什么我必须创建一个指针,而不是一个变量?

以下是不使用指针的方法 (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';
}