将成员功能实现为外部功能

Implementing a member function as an external function

本文关键字:功能 外部 实现 成员      更新时间:2023-10-16

我刚刚开始我的高级数据结构类,在处理类基础时,我们的问题之一是"将成员函数max()实现为外部函数。"

我已经浏览了C++入门、C编程语言和我们的文本,但都只提到了外部变量声明,并谈到了它作为某种全局快捷方式的使用。

有人能帮我弄清楚如何在外部实现我的会员功能,并帮助我理解提出这个问题的书背后的逻辑吗?

我的代码:

democlass.h

#ifndef Assignment_1_democlass_h
#define Assignment_1_democlass_h
class demoClass
{
public:
    demoClass(int a = 5, int b = 10);
    int max() const;
    int getA() const; //my added code, not in provided text example
    int getB() const; //my added code, not in provided text example
private:
    int itemA, itemB;
};
#endif

main.cpp

#include "democlass.h"
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
    demoClass obj1(7,9);
    demoClass obj2(12);
    demoClass obj3;
    cout << obj1.getA() << " " << obj1.getB() << endl;
    cout << obj2.getA() << " " << obj2.getB() << endl;
    cout << obj3.getA() << " " << obj3.getB() << endl;
    cout << endl;
    cout << obj2.max() << endl << obj3.max();
    return 0;
}
demoClass::demoClass(int a, int b){
    itemA = a;
    itemB = b;
}
int demoClass::max() const{
    if (itemA > itemB)
        return itemA;
    else
        return itemB;
};
int demoClass::getA() const{
    return itemA;
};
int demoClass::getB() const{
    return itemB;
};

下面的代码能工作吗?

inline int max(const demoClass& demo)
{
    return demo.max();
}