Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have that common LNK2019 error and can not figure out what is wrong.

Here is my Solution Explorer:

enter image description here

Here is my Rectangle.cpp:

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

Here is my Rectangle.h:

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

Here is my Functions.cpp:

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

using namespace std;

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

    return 0;
}

I am very new to C++ and it seems I did everything correctly, but still I am getting an error.

like image 920
some1 here Avatar asked Aug 10 '17 16:08

some1 here


2 Answers

Rectangle.cpp should be like this:

#include "Rectangle.h"

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

You shouldn't redefine the class definition in the source file, since you already have it in the header file!

like image 91
gsamaras Avatar answered Sep 21 '22 20:09

gsamaras


When you want to write the body of a class function, you need to write it this way :

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

You do not need to redefine your class into the cpp file. You define everything inside the header (.h, .hpp), you include it inside the cpp file (#include "Rectangle.h") but you must not redeclare everything in the header file.

By the way, since you are writing a method, you can access member variables directly by width and you do not need to use this->width.

However, I recommand you to use a convention when you are writing your own classes. My convention is to prefix member variable by a m. (In your case it gives you mWidth or mHeight).

There is other people that have other conventions like m_variable or variable_.

like image 28
Antoine Morrier Avatar answered Sep 19 '22 20:09

Antoine Morrier