Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member reference base type 'double' is not a structure or union

Tags:

c++

I'm new to C++ and can't figure out how to fix the error, would greatly appreciate for your help The part where the error occurs I'm trying to input the radius into the cirArea[] array, but it does not seem to work.

Here's a part of my code:

int main(){
    Circle *area;
    double cirRadius;
    int numCircle;

    cout << "How many circles?" << endl;
    cin >> numCircle;
    double cirArea[numCircle];

    for (int i = 0; i < numCircle; i++){
        cout << "Enter the radius: ";
        cin >> cirRadius;
        cirArea[i].setRadius(cirRadius);
    }
}

For setRadius():

void Circle::setRadius(double r){
    if (r >= 0)
        radius = r;
    else {
        cout << "Invalid radius\n";
        exit(EXIT_FAILURE);
    }
}

so here's the ERROR:

member reference base type 'double' is not a structure or union
            cirArea[i].setRadius(cirRadius);
            ~~~~~~~~~~^~~~~~~~~~
like image 780
Stephanieee Avatar asked Mar 22 '16 08:03

Stephanieee


2 Answers

You cannot create an statically allocated array with 'not a constant size'. Second issue is that cirArea is not of Circle type but of double.

You would have to allocate it dynamically (and delete it afterwards) and make it Circle type:

int main(){
    double cirRadius;
    int numCircle;

    cout << "How many circles?" << endl;
    cin >> numCircle;
    Circle *area = new Circle[numCircle];

    for (int i = 0; i < numCircle; i++){
        cout << "Enter the radius: ";
        cin >> cirRadius;
        cirArea[i].setRadius(cirRadius);
    }

    delete[] area;
}

But a preferable way of doing it would be to use a std::vector

#include <iostream>
#include <cstdlib>
#include <vector>

struct Circle
{
    double radius;

    void setRadius(double r){
        if (r >= 0)
            radius = r;
        else {
            std::cout << "Invalid radius\n";
            exit(EXIT_FAILURE);
        }
    }    
}   ; 

int main(){
    double cirRadius;
    int numCircle;

    std::cout << "How many circles?\n";
    std::cin >> numCircle;
    std::vector<Circle> area;
    area.reserve(numCircle);

    for (int i = 0; i < numCircle; ++i){
        std::cout << "Enter the radius: ";
        std::cin >> cirRadius;
        area.emplace_back();
        area.back().setRadius(cirRadius);
    }

    for( Circle& i : area )
    {
      std::cout << i.radius << '\n';
    }
}

http://cpp.sh/3l7ti

like image 99
Patryk Avatar answered Sep 23 '22 05:09

Patryk


Your cirArea has a type double, not Circle, so you cant't apply on it Circle method. Change the type of cirArea from double to Circule to fix the error.

like image 40
Mira Avatar answered Sep 22 '22 05:09

Mira