如何构建函数用指针比较大小

#include <iostream>
class A {
    int x;
public:
    A(int x) : x(x) {}
// GetX, Max 构建函数
};
 
int main() {
    const A a1(10);
    A a2(5), a3(3);
    std::cout << a1.GetX() << std::endl; // 10 输出
    std::cout << a2.GetX() << std::endl; // 5 输出
 
    A *p = a2.Max(&a3); // Max:a2.x和a3.x比较
                                // 返回值较大的实例地址
    std::cout << p->GetX() << std::endl; // 5输出
}
阅读 1.2k
1 个回答

这是你想要的吗?

class A {
    int x;
public:
    A(int x) : x(x) {}
    // GetX, Max 构建函数
    int GetX() const 
    {
        return x;
    }

    A* Max(A* other)
    {
        if (x > other->x)
            return this;
        return other;
    }
};
推荐问题