在类中嵌套对象

Nesting an object in a class

本文关键字:对象 嵌套      更新时间:2023-10-16

使用C++,我试图将一个类的对象嵌套在另一个类中,在CarpetClass.h的第6行出现语法错误,显示

错误:函数"矩形"不是类型名称

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;
    }
};

地毯等级.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);
    }
};   

源.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;
}

我不知道为什么我会收到一个错误——我把示例代码从课本里抄了出来。我尝试将这两个类放在我的cpp文件中,并将它们放在同一个头文件中。这两种解决方案都不起作用。请帮助我理解为什么会出现此错误。

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

class Rectangle将使编译器理解你指的是类名,而不是"使用设备上下文绘制矩形的Windows函数">

使用名称空间来避免名称冲突是一种很好的做法。或者,使用类似"用C前缀类名"的约定,即class CRectangle{...,这样它就不会与类似函数的名称

冲突

使用这个非常简单的驱动程序代码:

#include "CarpetClass.h"
int main()
{
    Carpet c;
}

代码在Linux下使用gcc干净地编译,但如果我修复了成员函数,则

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

您是否确保没有包含任何定义Rectangle的其他内容?您可能还想在头中插入一些#include保护,并提供默认的构造函数和析构函数。

要问一个更好的问题,下次可以尝试直接从电脑上剪切和粘贴代码(以及错误消息!(,以避免浪费时间。