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

时间:2018-01-08 03:13:26

标签: c++ function struct return 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

CPP:

    #include "Food.h"

    Food::Food()
    {
    }

    Food::~Food()
    {
    }

    Fruit Food::Person::setFavorite(Fruit newFav)
    {
        return newFav;
    }

主:

    #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");
    }

我的错误是:

  

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

     

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

如何解决这些问题并且有更好的方法来编写此代码吗?

2 个答案:

答案 0 :(得分:5)

identifier "Fruit" is undefined

此错误表示Fruit没有定义。

您已定义嵌套在Fruit内的班级Food。因此,从其他错误消息中可以看出该类的完全限定名称为Food::Fruit

declaration is incompatible with "Food::Fruit Food::Person::setFavorite(Food::Fruit newFav)"
                                  ^^^^^^^^^^^

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

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

auto Food::Person::setFavorite(Fruit newFav) -> Fruit

答案 1 :(得分:1)

除了公认的答案,OP的课堂设计也可以在我看来改进。 OP似乎想要创建一个与食品类有关系的水果类。让它成为食品类的一员对我来说似乎并不合适。同样的事情适用于Person类,它应该是一个独立的类而不是食物的成员。

#include <string>

class Food
{
    std::string m_name;
        // other stuffs...
};

class Fruit : public Food
{
    // unique fruit members and functions...
};

class Person
{
    Fruit m_favorite;

public:
    void SetFavorite(Fruit favorite);
};

void Person::SetFavorite(Fruit favorite)
{
    m_favorite = favorite;
}

int main()
{
    Fruit apple;
    Person fred;
    fred.SetFavorite(apple);

    return 0;
}
相关问题