#include <iostream>
using std::cout;
using std::endl;
class square {
public:
double length, width;
square(double length, double width);
square();
~square();
double perimeter();
};
double square::perimeter() {
return 2*square.length + 2*square.width;
}
int main() {
square sq(4.0, 4.0);
cout << sq.perimeter() << endl;
return 0;
}
I'm trying to write a simple class program. I am getting the error
in member function 'double square::perimeter()';
.cpp:21: error: expected primary-expression before '.' token
.cpp:21: error: expected primary-expression before '.' token
Does this mean I have to use 2*square::length + 2*square::width
?
square
is a type, not an object; instead of
return 2*square.length + 2*square.width;
do
return 2*length + 2*width;
(which is implicitly the same as:
return 2*this->length + 2*this->width;
which you may, or please may not, prefer for clarity).
2*square::length + 2*square::width
would be valid syntax if length
and width
were
square
, orsquare
, orsquare
Yes, the accurate form would be:
return 2*square::length + 2*square::width;
since square
is a type, not an object.
In this context, it's the same as:
return 2*this->square::length + 2*this->square::width;
However, since it's the same object and the same type, you can just write:
return 2*this->length + 2*this->width;
or, most simply:
return 2*length + 2*width;
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