c++ Xcode expected '(' for function-style

2019-09-08 02:47发布

问题:

I'm trying to compile this cpp and h files but it keeps giving me this error "expected '(' for function-style cast or type construction" and it points to the constructor

GasTank::GasTank(double a){
    capacity=a;
}

Any thoughts why? I can't figure it out why it is giving me that error. Here is the rest of the code:

//
//  Header.h
//  labs
//
//  Created by Pxndroid on 10/17/14.
//  Copyright (c) 2014 Pxndroid. All rights reserved.
//

#include<string>

using namespace std;

class GasTank
{
private:
    double amount;
    double capacity;

public:
    GasTank(double a);
    void addGas(double b);
    void useGas(double c);
    bool isEmpty();
    bool isFull();
    double getGasLevel();
    double fillUp();

};

and:

//
//  main.cpp
//  labs
//
//  Created by Pxndroid on 10/17/14.
//  Copyright (c) 2014 Pxndroid. All rights reserved.
//

#include <iostream>
#include "Header.h"

using namespace std;

int main()
{

    GasTank::GasTank(double a){
        capacity=a;
    }

    void GasTank::addGas(double b){
        if((amount+b)>capacity){
            amount=capacity;
        }
        else{
            amount+=b;
        }
    }

    void GasTank::useGas(double c){
        if((amount-c)<0){
            amount=0;
        }
        else{
            amount-=c;
        }
    }

    bool GasTank::isEmpty(){
        if(amount<0.1){
            return true;
        }
        else{
            return false;
        }
    }

    bool GasTank::isFull(){
        if(amount>capacity-0.1){
            return true;
        }
        else{
            return false;
        }
    }

    double GasTank::getGasLevel(){
        return amount;
    }

    double GasTank::fillUp(){
        capacity-=amount;
        amount+=capacity;

        return capacity;
    }
}

回答1:

Move the definitions of the GasTank members outside of int main(). They don't belong there, and the compiler is not expecting them; they are not part of the main() function.