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

#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;
    }
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题