C++ 从类的方法返回结构中的值 #包括 使用名称空间std; 结构AccountInfo { int-Acnumber; 字符ID; }; 类别帐户 { 公众: AccountInfo操作(作废) { 会计信息系统; s、 ID='M'; 返回s; } }; int main() { 账户a; AccountInfo s=a.操作(); 不能将struct更改为AccountInfo,初始声明除外。
将C++ 从类的方法返回结构中的值 #包括 使用名称空间std; 结构AccountInfo { int-Acnumber; 字符ID; }; 类别帐户 { 公众: AccountInfo操作(作废) { 会计信息系统; s、 ID='M'; 返回s; } }; int main() { 账户a; AccountInfo s=a.操作(); 不能将struct更改为AccountInfo,初始声明除外。,c++,methods,struct,C++,Methods,Struct,将struct更改为AccountInfo,初始声明除外 #include <iostream> using namespace std; struct AccountInfo { int Acnumber; char ID; }; class Account { public: AccountInfo Operation(void) { AccountInfo s; s.ID
struct
更改为AccountInfo
,初始声明除外
#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;
}
此函数返回什么类型?它不能是struct
,因为它不是一个类型,而是一个表示结构定义的关键字。从返回值和使用方法来看,我假设您试图返回AccountInfo
对象:
struct Operation(void)
空参数也不需要使用void
。此外,还需要在main()
AccountInfo
中设置s
的类型:
AccountInfo Operation()
{
AccountInfo s;
s.ID = 'M';
return s;
}
此函数返回什么类型?它不能是struct
,因为它不是一个类型,而是一个表示结构定义的关键字。从返回值和使用方法来看,我假设您试图返回AccountInfo
对象:
struct Operation(void)
空参数也不需要使用void
。此外,还需要在main()
AccountInfo
中设置s
的类型:
AccountInfo Operation()
{
AccountInfo s;
s.ID = 'M';
return s;
}
你“尝试使用对象”是什么意思?我定义了一个类,并在Account类中创建了该类的对象,而不是struct。请显示该代码。#包括使用名称空间std;class AccountInfo{public:int Acnumber;char ID;};class Account{public:AccountInfo操作(void){AccountInfo s;s.ID='M';返回s;}};int main(){Account a;AccountInfo s=a.Operation();cout当我运行代码时,编译器会告诉我类定义后缺少分号,并且您试图从
AccountInfo
对象访问的数据成员是私有的。若要解决此问题,请在Account
类的末尾大括号中添加分号;
,然后在上方添加public:
AccountInfo
的数据成员。或者将AccountInfo
设置为struct
而不是class
,从而使其成员在默认情况下可公开访问。您“尝试使用对象”是什么意思?我定义了一个类,并在Account类中创建了该类的对象,而不是struct。您能显示该代码吗?#使用名称空间std包含;类AccountInfo{public:int Acnumber;char ID;};类Account{public:AccountInfo操作(void){AccountInfo s;s.ID='M';返回s;}};int main(){Account a;AccountInfo s=a.Operation();cout当我运行代码时,编译器会告诉我类定义后缺少分号,并且您试图从AccountInfo
对象访问的数据成员是私有的。若要解决此问题,请在Account
类的末尾大括号中添加分号;
,然后在上方添加public:
AccountInfo
的数据成员。要么这样,要么使AccountInfo
成为struct
而不是class
,从而使其成员在默认情况下可以公开访问。对不起,这是一个输入错误。我必须用AccountInfo代替struct。我只是想在输出中得到M。这可能吗?@Pgr我当然有可能。如果你完全执行我给你的建议,你会得到正确的输出。太棒了,谢谢0x499602D2先生。我还有一个简单的问题。有没有可能在不初始化s即AccountInfo s=a.Operation()的情况下获得输出;是否有类似于(a.Operation()的内容).ID?@Pgram一点问题都没有。你介意接受我的回答吗?:)我通过用方法替换struct来更改代码,代码是相同的,它不返回对象。这里有问题吗?抱歉,没错。这是一个打字错误。我必须用AccountInfo替换struct。我只是想在输出中得到M。这可能吗?@Pgram当然有可能。如果你完全执行我给你的建议,你会得到正确的输出。太棒了,谢谢0x499602D2先生。我还有一个简单的问题。是否可以在不初始化s的情况下获得输出,即AccountInfo s=a.Operation();是否有类似(a.Operation()).ID?@Pgram没问题。你介意接受我的回答吗?:)我用方法替换struct来更改代码,代码是相同的,它不返回对象。这里有问题吗?