尝试初始化"rect"时类"rect"无效使用 (C++)

invalid use of class "rect" when trying to initialise a "rect" (c++)

本文关键字:rect C++ 时类 初始化 无效      更新时间:2023-10-16

已解决:

我的错误是使用dot而不是=因此更改:

myRect.Rect(pt1,pt2,pt3,pt4); <-- didn't work
myRect = Rect(pt1,pt2,pt3,pt4); <-- worked

(感谢您的快速帮助!即使为这个问题获得-1)

初始问题:

我试图使我的问题尽可能简单。我不知道为什么这不起作用。如何更改创建的rect的点?我的猜测是我无法与" this ->操作员"正确地工作。

我什至不知道如何正确地将我的问题标记为更好的标签?

point.h

class Point
{
private:
public:
    int X;
    int Y;
};

point.cpp

Point::Point() {
    X = 0;
    Y = 0;
}

rect.h

class Rect
{
private:
    Point P1, P2, P3, P4;
public:
    Rect();
    Rect(Point p1, Point p2, Point p3, Point p4);
};

rect.cpp

Rect::Rect(Point p1, Point p2, Point p3, Point p4) {
    this -> P1 = p1;
    this -> P2 = p2;
    this -> P3 = p3;
    this -> P4 = p4;
}

main.cpp

int main(){
    Rect myRect;
    Point pt1;
    Point pt2;
    Point pt3;
    Point pt4;
    myRect.Rect(pt1,pt2,pt3,pt4);
}

errormessage:

'Rect::Rect'

的使用无效

您正在误解方法的构造函数。看看这个问题的答案(这是关于Java,但适用类似的想法):https://stackoverflow.com/a/25803084/4816518。

总结,使用构造函数(包括默认构造函数)来初始化对象,不要返回任何内容(如果不包括要创建的对象),则命名与类相同(例如,Rect::RectRect类的构造函数。
另一方面,方法用于在已经创建的对象上调用某些行为。另外,与构造函数不同,它们 can 具有返回类型。

所以,而不是这个

Rect myRect;
Point pt1;
Point pt2;
Point pt3;
Point pt4;
myRect.Rect(pt1,pt2,pt3,pt4);

您可能想要更多的东西:

Point pt1 = Point(0,0); //Didn't see this constructor, but you probably need it.
Point pt2 = Point(1,1); //I'm choosing random values.
Point pt3 = Point(0,1);
Point pt4 = Point(1,0);
myRect = Rect(pt1,pt2,pt3,pt4); //this creates the Rect with the given points.

或以下:

Point pt1(0,0);
Point pt2(1,1);
Point pt3(0,1);
Point pt4(1,0);
Rect myRect(pt1,pt2,pt3,pt4);

,甚至这个更简单的版本(但是,您需要声明Point::Point(int x, iny y)构造函数,并且Rect的构造函数需要使用const Point&参数)。

Rect myRect(Point(0,0),Point(1,1),Point(0,1),Point(1,0));

构造函数(在您的情况下,Point::Point()Rect::Rect(Point p1, Point p2, Point p3, Point p4)),创建对象,然后然后您可以在其上执行方法。

Rect myRect声明一个变量,并使用默认构造函数实例化。如果要将参数传递给对象,则需要调用带有Rect(Point p1, Point p2, Point p3, Point p4)等参数的构造函数。

有两个错误。

1。您需要声明Point的默认构造函数,以创建您在类外部定义的构造函数。

class Point
{
private:
public:
    Point(); // <-- add this
    int X;
    int Y;
};

2。您无需使用类访问点运算符即可使用Rect()。这是因为Rect()是一个构造函数,并且不需要像函数那样在对象上调用构造函数。

Rect myRect;
myRect = Rect(pt1,pt2,pt3,pt4);

Rect myRect = Rect(pt1,pt2,pt3,pt4);

Rect myRect(pt1,pt2,pt3,pt4);

您首先使用默认构造函数(Rect::Rect())构造myRect,然后尝试将另一个构造函数称为成员函数。(这是无效的使用)

而是直接使用其他构造函数:Rect myRect(p1, p2, p3, p4)

关于this->P1,您不需要使用this访问成员变量。对于构造函数,使用初始化列表作为 Rect(Point p1, Point p2, Point p3, Point p4) :P1{p1},P2{p2},P3{p3},P4{p4} {}更喜欢在构造体主体中进行分配,出于相同的原因:如果您不初始化成员,则将在输入构造函数之前默认构建。