conversion error
Why am I getting this error when I compile code?
error: conversion from 'rectangle*' to non-scalar type 'rectangle' requested
my class is in a header file named rectangle.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <cmath>
class rectangle
{
private:
int length,width;
public:
rectangle(int x,int y);
virtual ~rectangle();
int area()
{ int a = length * width;
return a;
}
int perimeter()
{ int b = 2*(length * width);
return b;
}
}
int diagonal()
{ int c= sqrt(length * width);
return c;
}
};
#endif // RECTANGLE_H
|
here's my main function
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
rectangle rect = new rectangle(3,4);
cout<<rect.area()<<endl;
cout<<rect.perimeter()<<endl;
return 0;
}
|
Made a few changes to fix it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <cmath>
class rectangle
{
private:
int length,width;
public:
rectangle() = default; // this is needed
rectangle(int x,int y) : length(x), width(y) {} // changed
// removed virtual ~rectangle();
int area()
{ int a = length * width;
return a;
}
int perimeter()
{ int b = 2*(length * width);
return b;
}
// removed '}'
int diagonal()
{ int c= sqrt(length * width);
return c;
}
};
#endif // RECTANGLE_H
|
Last edited on
Change rectangle rect = new rectangle(3,4);
to rectangle rect(3,4);
Another way is to recognise that new generates a pointer so:
1 2 3
|
rectangle* rect = new rectangle(3, 4);
cout << rect->area() << endl;
cout << rect->perimeter() << endl;
|
Thank you kemort.
Topic archived. No new replies allowed.