LNK2019案例如何解决?一切似乎都是正确的

LNK2019 how to solve in the case? Everything seems to be correct

我有那个常见的 LNK2019 错误,无法弄清楚问题出在哪里。

这是我的解决方案资源管理器:

这是我的 Rectangle.cpp:

class Rectangle
{
    public:
        int getArea()
        {
            return this->width*this->height;
        }
        int width;
        int height;
};

这是我的 Rectangle.h:

#pragma once
class Rectangle
{
    public:
        int getArea();
        int width;
        int height;
};

这是我的 Functions.cpp:

#include <iostream>
#include "Rectangle.h";

using namespace std;

int main()
{
    Rectangle r3{ 2, 3 };
    cout << r3.getArea();

    return 0;
}

我是 C++ 的新手,似乎我做的一切都是正确的,但我仍然遇到错误。

当你想写一个class函数的body时,你需要这样写:

#include "Rectangle.h"
int Rectangle::getArea()
{
    return this->width*this->height;
}

您不需要将 class 重新定义到 cpp 文件中。 您在 header (.h, .hpp) 中定义所有内容,将其包含在 cpp 文件 (#include "Rectangle.h") 中,但您不得在 header 文件中重新声明所有内容。

对了,既然你写的是方法,那么直接用width访问成员变量就可以了,不需要用this->width.

但是,我建议您在编写自己的 classes 时使用约定。 我的约定是在成员变量前加上 m。 (在你的情况下,它给你 mWidthmHeight)。

还有其他人有其他约定,例如 m_variablevariable_

Rectangle.cpp应该是这样的:

#include "Rectangle.h"

int Rectangle::getArea() {
  return this->width*this->height;
}

你不应该在源文件中重新定义 class 定义,因为你已经在头文件中有了它!