gpt4 book ai didi

c++ - 头文件。 ETC

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:20:15 24 4
gpt4 key购买 nike

我定义了一个简单的类。定义在头文件中,实现在cpp文件中:

标题:

#ifndef POINT_H
#define POINT_H

class Point {
public:
Point(int x, int y);

int getX();
int getY();

private:
int x, y;
};

#endif

CPP

#include Point.h

Point::Point(int x=2, int y=2) {
this->x = x;
this->y = y;
}

int Point::getX() {
return x;
}

int Point::getY() {
return y;
}

这不是编译,我不确定为什么。另外,当我想实例化一个点时在其他地方,比如 main.cpp,我在顶部 #include 是什么,只是 Point.h?如果是这样,它怎么知道要查看 Point.cpp?

最佳答案

#include Point.h 

Point.h 需要引号。

Point::Point(int x=2, int y=2) 

默认参数应该在头文件的声明中,而不是在 .cpp 文件的定义中(它将按原样编译,但不会执行您想要的操作)。

在文体上,将局部变量或参数命名为与成员变量相同的名称通常不是一个好主意:这样做很容易导致混淆。您还可以使用初始化列表初始化成员变量:

Point::Point(int x_, int y_) : x(x_), y(y_) { }

由于您当前编写的代码,xy 均已构造,然后您将其赋值给它们。使用初始化列表消除了分配并直接构造它们。这对于 int 等基本类型无关紧要,但对于类类型却很重要。

This is not compiling and I am not sure why.

通常编译器发出的错误信息是有帮助的。如果不出意外,如果它对您没有帮助,那么它对我们这些试图提供帮助的人很有帮助。

Also, when I want to instantiate a point somewhere else, say main.cpp, what do I #include at the top, just Point.h?

是的。

How does it know to look in Point.cpp?

您编写的每个 .cpp 文件都会编译成一个单独的目标文件。一旦所有 .cpp 文件都编译成目标文件,目标文件就会全部链接在一起成为一个可执行文件(或库)。链接器找出所有内容的定义位置。

关于c++ - 头文件。 ETC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5422665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com