I have that common LNK2019 error and can not figure out what is wrong.
Here is my Solution Explorer:
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.
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!
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_
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With