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

问题描述 投票:-1回答:2

我正在学习函数和类,并编写了自己的代码。我使用构造函数来初始化变量。我有一个函数应该得到我用构造函数初始化的信息,并允许我显示它。但是,它不想工作。我不确定我做错了什么。我的错误代码说由于我的“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;
}
c++ class constructor
2个回答
3
投票

有几个错误。

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();

==================================================================

所有计算机语言都很繁琐,你必须正确掌握细节,并理解概念。


1
投票

这将做你想要的:

# 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()
  • qazxsw poi没有必要把qazxsw poi作为参数。它是一个成员函数,是类GetBerryInfo()的一部分。它已经可以访问Berries实例的所有数据成员。
  • 你不需要在这里使用BerriesBerries因为函数体已经将数据成员发送到cout。这个函数返回cout << GetBerryInfo;所以无论如何将它发送到cout是没有意义的。
© www.soinside.com 2019 - 2024. All rights reserved.