从类的方法返回结构中的值

时间:2014-02-04 20:26:05

标签: c++ methods struct

#include <iostream>
using namespace std;

struct AccountInfo
{
    int Acnumber;
    char ID;
};

class Account
{
    public:
        AccountInfo Operation(void)
        {
            AccountInfo s;
            s.ID = 'M';
            return s;

        }
};

int main()
{
    Account a;
    AccountInfo s = a.Operation();
    cout << s.ID << endl;

    return 0;
}     

我试图将给出的值赋给类方法中的结构。代码编译错误。我尝试使用一个对象,它成功编译,但不输出任何东西。

我的代码有什么问题?

2 个答案:

答案 0 :(得分:3)

struct Operation(void)

此功能返回什么类型?它不能是struct,因为它不是一个类型,它是一个表示结构定义的关键字。从返回值以及您如何使用它来判断,我假设您正在尝试返回AccountInfo对象:

AccountInfo Operation()
{
    AccountInfo s;
    s.ID = 'M';
    return s;
}

空参数也不需要void。此外,您还需要在s main()中设置AccountInfo的类型:

int main()
{
    Account a;
    AccountInfo s = a.Operation();
}

答案 1 :(得分:1)

除了初始声明之外,将struct更改为AccountInfo