在类中嵌套对象
Nesting an object in a class
使用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
保护,并提供默认的构造函数和析构函数。
要问一个更好的问题,下次可以尝试直接从电脑上剪切和粘贴代码(以及错误消息!(,以避免浪费时间。
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 将 AActor 引用传递到嵌套对象中
- 通过 id 访问 QML 插槽中的嵌套对象(从 c++ 调用)
- 我们可以在main函数中声明嵌套类对象吗
- 访问另一个类中的模板化嵌套类函数和对象
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- RapidJSON 文档创建嵌套对象
- Poco 迭代嵌套的 JSON 对象
- 具有嵌套对象优化的 C++ emplace_back
- 使用MPI/OpenMP的C 程序带有派生数据类型(嵌套类对象)容器
- 设计具有两个指向嵌套对象的指针的迭代器
- 如果嵌套对象具有相同的地址,编译器如何区分它们?
- C++ 在 std::set 的嵌套对中搜索对象
- 创建嵌套类中的对象
- C nlohmann如何迭代 /查找嵌套对象
- 堆上是否会分配内存以支持临时对象到常量引用的嵌套绑定
- 我想在C++中创建内部类的对象,或者可能是嵌套类
- 嵌套的lambda表达式在用Visual C++编译和生成巨大的对象文件时速度非常慢
- 如何从C++访问嵌套的 QML 对象
- C++:特定于友元的对象(嵌套类)