我正在学习函数和类,并编写了自己的代码。我使用构造函数来初始化变量。我有一个函数应该得到我用构造函数初始化的信息,并允许我显示它。但是,它不想工作。我不确定我做错了什么。我的错误代码说由于我的“void”函数,我有未解析的外部。我认为我的函数没有返回任何东西,只是显示它从构造函数的初始化得到的输入。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
};
void GetBerryInfo (const Berries& B);
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
cout << GetBerryInfo;
system("pause");
return 0;
}
有几个错误。
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
应该
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
==================================================================
void GetBerryInfo (const Berries& B);
应该删除。
==================================================================
cout << GetBerryInfo;
应该
Berryinfo1.GetBerryInfo();
==================================================================
所有计算机语言都很繁琐,你必须正确掌握细节,并理解概念。
这将做你想要的:
# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
};
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
Berryinfo1.GetBerryInfo();
system("pause");
return 0;
}
你的错误有两点:
GetBerryInfo()
在课堂上被宣布。您无需在全局范围内重新声明它。应该删除第二个声明。GetBerryInfo
)必须在它们的末尾有()
,如:GetBerryInfo()
。GetBerryInfo()
的一部分。它已经可以访问Berries
实例的所有数据成员。Berries
:Berries
因为函数体已经将数据成员发送到cout
。这个函数返回cout << GetBerryInfo;
所以无论如何将它发送到cout
是没有意义的。