访问C++中的嵌套类

Accessing nested class in C++

本文关键字:嵌套 C++ 访问      更新时间:2023-10-16

我在一次在线测试中遇到了这个问题。任务是修改这个程序以消除编译错误。

#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"的成员

一旦修复了另外两个问题,此错误就会消失。编译器无法解析函数声明,因为它不知道它的返回类型是什么。