如何在c ++中返回自己的结构?

0 c++ struct return function visual-studio-2017

我在创建一个返回我自己的struct的函数时遇到了麻烦.

标题:

    #ifndef FOOD_H
    #define FOOD_H
    #include <string>

    class Food
    {
    public:
        Food();
        ~Food();
    public:
        struct Fruit {
            std::string name;

        };
        struct Person {
            Fruit favorite;
            Fruit setFavorite(Fruit newFav);
        };

    public:
        Fruit apple;
        Fruit banana;

        Person Fred;
    };
    #endif
Run Code Online (Sandbox Code Playgroud)

CPP:

    #include "Food.h"

    Food::Food()
    {
    }

    Food::~Food()
    {
    }

    Fruit Food::Person::setFavorite(Fruit newFav)
    {
        return newFav;
    }
Run Code Online (Sandbox Code Playgroud)

主要:

    #include "Food.h"
    #include <iostream>

    int main() {
        Food fd;    
        fd.Fred.favorite = fd.Fred.setFavorite(fd.apple);
        std::cout << fd.Fred.favorite.name;
        system("pause");
    }
Run Code Online (Sandbox Code Playgroud)

我的错误是:

E0020标识符"Fruit"未定义Food.cpp 11

E0147声明与"Food :: Fruit Food :: Person :: setFavorite(Food :: Fruit newFav)"(在Food.h第17行声明)不相容Food.cpp 11

我如何解决这些问题,是否有更好的方法来编写此代码?

eer*_*ika 5

identifier "Fruit" is undefined
Run Code Online (Sandbox Code Playgroud)

此错误表示没有定义Fruit.

您已经定义了一个Fruit嵌套在其中的类Food.因此,Food::Fruit从其他错误消息可以看出该类的完全限定名称:

declaration is incompatible with "Food::Fruit Food::Person::setFavorite(Food::Fruit newFav)"
                                  ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

此错误消息告诉您声明Food::Person::setFavorite(Fruit newFav)是不兼容的,因为该函数应该返回Food::Fruit而不是Fruit(这是没有定义的东西).


Fruit可以用来Food::Fruit在类的上下文中引用Food.此函数的定义在类之外,因此它不在上下文中.直到function(Food::Person::setFavorite)的名称才建立上下文.您可以使用尾随返回类型来避免使用完全限定类型:

auto Food::Person::setFavorite(Fruit newFav) -> Fruit
Run Code Online (Sandbox Code Playgroud)