访问C++中的嵌套类
Accessing nested class in C++
我在一次在线测试中遇到了这个问题。任务是修改这个程序以消除编译错误。
#include<iostream>
#include<iomanip>
class Vehicle
{
public:
static Car* createCar()
{
return new Car;
}
class Car
{
public:
string name;
};
private:
int seats;
};
void useVehicle()
{
Vehicle::Car *c = Vehicle::createCar();
c->name = "BMW";
}
int main(int argc, char *argv[])
{
useVehicle();
return 0;
}
编译错误如下:error: ‘Car’ does not name a type
error: ‘string’ does not name a type
在函数void useVehicle()
中:error: ‘createCar’ is not a member of ‘Vehicle’
我该怎么做?我尝试了几件事,但都没能解决这些错误。
错误:"Car"没有命名类型
在点
static Car* createCar()
汽车还不为人所知。将类Car
的定义移动到函数之上
错误:"string"未命名函数"void useVehicle()"中的类型:
#include <string>
也使用std::
来限定string
错误:"createCar"不是"Vehicle"的成员
一旦修复了另外两个问题,此错误就会消失。编译器无法解析函数声明,因为它不知道它的返回类型是什么。
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray