【问题标题】:return the value in a struct from method of a class从类的方法返回结构中的值
【发布时间】:2014-03-01 00:31:48
【问题描述】:
#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;
}     

我正在尝试返回给定给类方法内部结构的值。代码编译时出现错误。我尝试使用一个对象,它编译成功,但不输出任何东西。

我的代码有什么问题?

【问题讨论】:

  • 您“尝试使用对象”是什么意思?
  • 我定义了一个类并在 Account 类中创建了该类的对象,而不是 struct。
  • 请您出示该代码。
  • #include 使用命名空间标准;类 AccountInfo { public: int Acnumber;字符 ID; };类 Account { public: AccountInfo Operation(void) { AccountInfo s; s.ID = 'M';返回 s; } }; int main() { 帐户 a; AccountInfo s = a.Operation(); cout
  • 当我运行您的代码时,编译器告诉我您在类定义后缺少分号,并且您尝试从 AccountInfo 对象访问的数据成员是私有的。要解决此问题,请在Account 类的末尾大括号处添加分号;,并在AccountInfo 的数据成员上添加public:。要么这样做,要么将AccountInfo 设为struct 而不是class,从而使其成员默认可公开访问。

标签: c++ methods struct


【解决方案1】:
struct Operation(void)

这个函数返回什么类型?不能是struct,因为那不是类型,而是表示结构定义的关键字。从返回值和你如何使用它来看,我假设你正在尝试返回一个AccountInfo 对象:

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

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

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

【讨论】:

  • 对不起,是的。这是一个错字。我必须用 AccountInfo 代替 struct。我只是想在我的输出中得到 M 。这可能吗?
  • @Pgram 当然有可能。如果您完全实施我给您的建议,您将获得正确的输出。 Here is a working example.
  • 太棒了,感谢 0x499602D2 先生。我还有一个简短的问题。是否可以在不初始化 s 的情况下获得输出,即 AccountInfo s = a.Operation();有没有类似 (a.Operation()).ID 的东西?
  • @Pgram 完全没问题。你也介意接受我的回答吗? :)
  • 我通过用方法替换结构来更改代码并且代码相同,它不返回对象。这里有问题吗?
【解决方案2】:

struct 更改为AccountInfo,除了初始声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    相关资源
    最近更新 更多