[英]How do I return my own struct in c++?
我在创建返回自己的结构的函数时遇到了麻烦。
标头:
#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标识符“水果”未定义Food.cpp 11
E0147声明与“ Food :: Fruit Food :: Person :: setFavorite(Food :: Fruit newFav)”(在Food.h的第17行声明)不兼容。Food.cpp 11
我该如何解决这些问题,有没有更好的方法来编写此代码?
identifier "Fruit" is undefined
此错误表明对Fruit
没有定义。
您已经定义了一个嵌套在Food
Fruit
类。 因此,该类的完全限定名称为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
在我看来,除了可以接受的答案外,OP的班级设计也可以得到改进。 OP似乎想创建一个水果类,该水果类与食物类之间应具有is-a关系。 在我看来,让它成为美食界的一员似乎并不对。 同样的事情适用于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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.