在类中嵌套对象 [英] Nesting an object in a class
问题描述
使用C ++我试图将一个类的对象嵌套在另一个类中,并且在 CarpetClass.h
的第6行上出现语法错误,说
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
错误:fuctionRectangle不是类型名称
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;
}
我不知道为什么我得到一个错误我复制示例代码直接从我的教科书。我试着把这两个类放在我的cpp文件,也把它们放在同一个头文件。这些解决方案都没有工作。请帮助我理解为什么我得到这个错误。
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.
推荐答案
class Carpet{
private:
double pricePerSqYd;
class Rectangle size;
class Rectangle
你的意思是你的类的名字,而不是使用设备上下文绘制矩形的Windows函数
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"
使用命名空间避免名称冲突是一个好习惯。或者,使用一个约定,例如用 C 前缀类名,即类CRectangle {...
t与类似函数的名称冲突
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
这篇关于在类中嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!