【问题标题】:Is there any method to call class member functions?有没有调用类成员函数的方法?
【发布时间】:2020-05-10 06:38:59
【问题描述】:

有什么方法可以调用Purchase类的显示函数。

#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;
class Purchase
{
private:
string userName;
int countOfItems;  
float amount;
float static totalAmt;
int static totalCountOfItems;

public:

void display(Purchase obj[],int n)
{
    for(int i=0;i<n;i++)
    {
        setTotalAmt(obj[i].getTotalAmt()+obj[i].getAmount());
        setCountOfItems(obj[i].getCountOfItems()+obj[i].getCountOfItems());
    }
    cout<<"Total Amount Received :"<<getTotalAmount();
    cout<<"Total Number of Items sold :"<<getTotalCountOfItems();
}
};

getter 和 setter 已经是成员函数了。

如何在主函数中调用显示函数 我的主要功能是这样的:

#include <iostream>
#include<string>
#include<stdio.h>
#include "Purchase.cpp"
using namespace std;
int main()
{
    int n;
    string userName;
    int countOfItems;  
    float amount;
    cout<<"Enter the Number of customers :";
    cin>>n;
    Purchase P[n];
    for(int i=0;i<n;i++)
    {
        cin.ignore();
        cout<<"Enter the Name of the customer :";
        getline(cin,userName);
        P[i].setUserName(userName);
        cout<<"Enter the No of Items purchased :";
        cin>>countOfItems;
        P[i].setCountOfItems(countOfItems);
        cout<<"Enter the purchase amount :";
        cin>>amount;
        P[i].setAmount(amount);
    }
    cout<<"Purchase Details :";
    for(int i=0;i<n;i++)
    {
        cout<<"Customer "<<i+1<<" :"<<P[i].getUserName()<<endl;
        cout<<"No of Items purchased :"<<P[i].getCountOfItems()<<endl;
        cout<<"Purchase amount :"<<P[i].getAmount()<<endl;
    }
    cout<<"\n";
    return 0;
}

最后我必须添加显示函数的调用,以便我可以添加每个对象的数量和计数。

【问题讨论】:

  • 您在寻找static method吗?
  • 我不确定我是否理解你的问题,因为调用成员函数在 C++ 中是如此基本,以至于你不可能不被你用来学习的任何东西所覆盖。
  • 不,这是在https://app.e-box.co.in/ 中提出的问题,我无法更改签名。我能改变的只是显示和主要功能的定义。
  • 花几天时间阅读更多关于C++ programming的信息
  • Purchase P[n]; 使用 VLA extension,所以 C++ 无效,请改用 std::vector。

标签: c++ arrays class


【解决方案1】:

有没有调用类成员函数的方法?

您可以获取成员function 的地址并稍后传递。

但是对于 C++11 或更高版本(阅读 n3337,C++11 标准),请阅读 more about C++ 然后考虑使用 lambda-expressions。当然使用&lt;algorithm&gt;&lt;functional&gt; 标准头文件。

还要花时间阅读更多关于标准 containersstrings 的信息。

void display(Purchase obj[],int n)

为什么不能使用 void display_vect(std::vector&lt;Purchase&gt;&amp;vec); ?如果您无法更改display 的API,请考虑从您的display 成员函数中调用您的display_vect

阅读rule of five

【讨论】:

  • 我无法更改函数的签名。
  • 可以引入包装函数。
【解决方案2】:

我不完全确定问题是什么,或者您被要求做什么。但是很明显display不应该是Product的成员函数。 Product 的成员函数应该关注一个特定的产品,但 display 正在打印所有产品,所以它应该是一个独立的函数而不是成员函数。你的代码应该是这样的

class Product
{
    ...
};

void display(Purchase obj[],int n)
{
    ...
}

然后从main 调用它是微不足道的。

int main()
{
    ...
    display(P, n);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2019-08-29
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多