Nesting an object in a class [closed]

2019-09-19 10:48发布

问题:

Using C++ I'm trying to nest an object of one class inside another class and I get a syntax error on line 6 of CarpetClass.h that says

Error: fuction "Rectangle" is not a type name

myclass.h

class Rectangle{
private:
    double length;
    double width;
public:
    void setLength(double len){
        length = len;
    }
    void setWidth(double wid){
        width = wid;
    }
    double getLength(){
        return length;
    }
    double getWidth(){
        return width;
    }
    double getArea(){
        return length*width;
    }
};

CarpetClass.h

#include "myclass.h"

class Carpet{
private:
    double pricePerSqYd;
    Rectangle size;
public:
    void setPricePeryd(double p){
        pricePerSqYd = p;
    }
    void setDimensions (double len, double wid){
        size.setLength(len / 3);
        size.setWidth(wid / 3);
    }
    double getTotalPrice(){
        return (size.getArea*pricePerSqYd);
    }
};   

Source.cpp

#include <iostream>
#include "CarpetClass.h"
using namespace std;

int main(){
    Carpet purchase;
    double pricePerYd;
    double length;
    double width;

    cout << "Room length in feet: ";
    cin >> length;
    cout << "Room width in feet: ";
    cin >> width;
    cout << "Carpet price per sq. yard: ";
    cin >> pricePerYd;
    purchase.setDimensions(length, width);
    purchase.setPricePeryd(pricePerYd);
    cout << "\nThe total price of my new " << length << "x" << width << " carpet is $" << purchase.getTotalPrice() << endl;
}

I don't know why I'm getting an error I copied example code right out of my text book. I have tried putting both classes in my cpp file and also putting them both in the same header file. Neither of those solutions worked. Please help me understand why I'm getting this error.

回答1:

class Carpet{
private:
    double pricePerSqYd;
    class Rectangle size;

class Rectangle will make the compiler understand that you mean your class's name and not "Windows function to draw a rectangle using a device context"

It is a good practice to use namespaces to avoid name collisions. Or, alternatively, use a convention like "prepend a class name with a C", i.e. class CRectangle{... and then it won't collide with a similar function's name



回答2:

Using this very simple driver code:

#include "CarpetClass.h"

int main()
{
    Carpet c;
}

the code compiles cleanly under Linux using gcc, but only if I fix the member function:

double getTotalPrice(){
    return (size.getArea()*pricePerSqYd);
}

Have you made sure that you aren't including anything else that defines a Rectangle? You might also want to insert some #include guards in your headers, and provide default constructors and destructors.

To ask a better question, next time try cutting and pasting the code (and the error message!) directly from your computer to avoid time-wasting typos.