繁体   English   中英

如何使我的构造函数和函数起作用,以便我的main()能够同时显示字符串和int数据?

[英]How do I get my constructor and functions to work so my main() is able to display both the string and int data?

我正在学习函数和类,并编写了自己的代码。 我使用了构造函数来初始化变量。 我有一个功能,该功能应该获取我用构造函数初始化的信息,并允许我显示它。 但是,它不想工作。 我不太确定自己在做什么错。 我的错误代码表示由于我的“无效”功能,我无法解析外部因素。 我以为我的函数不会返回任何东西,而只是显示从构造函数的初始化中获得的输入。

#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实例的所有数据成员。
  • 您无需在此处使用coutcout << GetBerryInfo; 因为函数主体已经将数据成员发送到cout 该函数返回void因此无论如何将其发送给cout没有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM