将函数的类型声明为struct c ++

时间:2015-06-19 01:27:02

标签: c++ function class struct

所以我有这个名为User的类。在里面我创建了一个名为flight的结构,我想在这个类中创建一个函数来返回一个带有航班值的结构。那可能吗?像下面这样的东西。我知道它不起作用但有办法吗?

   Class User
   {
       string name, surname...;
       struct flights
       {
          int miles;
          double cost;
        }
     struct add_miles(reads from another class);
   }
    struct User::add_miles()
    {
        return flights;
     }

2 个答案:

答案 0 :(得分:1)

我不确定我清楚地理解你的要求,但看看我的尝试:

 #include<iostream>

class User
   {
       //string name, surname...;
       public:
       struct flights
       {
          int miles;
          double cost;
        }myflights;
     struct flights  add_miles()
     {
        return myflights;

     }
};


   int main()
   {
       User me;
       me.myflights.miles=100;
       std::cout<<me.add_miles().miles;

   }

答案 1 :(得分:0)

您必须让add_miles返回flights结构,而不仅仅是struct

示例代码:

#include <iostream>

using namespace std;

class User
{
    private:
        string name,
               surname;

    public:
        struct flights {
            int miles;
            double cost;
        };

        flights add_miles() {
            return flights();
        }
};

int main(int argc, char **argv) {
    User u;
    User::flights f = u.add_miles();
    cout << f.miles << endl;
    return 0;
}