2017-08-10 25 views
0

我有这个共同的LNK2019错误,并不能找出什么是错的。LNK2019如何解决的情况下?一切似乎是正确的

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

enter image description here

这里是我的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++非常陌生,看起来我做的都正确,但仍然出现错误。

+1

你为什么重新定义cpp文件中的'Rectangle'类?看到这个:https://stackoverflow.com/questions/9579930/separating-class-code-into-a-header-and-cpp-file – NathanOliver

+0

他是什么类? – ohidano

+0

@ohidano他指的是班级。看到我的答案! =) – gsamaras

回答

2

Rectangle.cpp应该是这样的:

#include "Rectangle.h" 

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

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

+0

现在我得到了LNK1120和相同的2019年。 – ohidano

+0

你究竟是什么意思@ohidano?你有没有在源文件中包含头文件,就像你在'main()'中做的那样? – gsamaras

+0

我解决了这个问题。看起来我必须在'.h'文件中只使用一次** class **一次,并且在编写类实现时我根本不会提到成员字段。我是否正确? – ohidano

2

如果你想写一类函数的身体,你需要将它这样写:

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

你并不需要重新定义你的班级分成cpp文件。 您可以定义头文件(.h,.hpp)中的所有内容,将其包含在cpp文件(#include "Rectangle.h")中,但不能重新声明头文件中的所有内容。

顺便说一下,由于您正在编写方法,因此您可以直接通过width访问成员变量,并且不需要使用this->width

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

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

+0

因此,在'.cpp'类文件中只有方法的实现应该去,我说得对吗? – ohidano

+0

@ohidano是的,没错!安托万,很好的答案! :) – gsamaras

+0

这取决于你需要什么。但我会说这样处理。 一个类= 2个文件:像你这样做的一个头(这是一种计划)和* .cpp中的构造。之后,这取决于你需要什么。但是自从你开始使用C++之后,我可以建议你像我们这样说: header = class和方法的原型。 CPP =实施 –

相关问题