两个简单问题~关于“类” “this”
问题见代码注释部分 谢谢
#include <iostream>//leleusing namespace std;class A{ private: int val;//比值对象 public: void voluation() { cin>>val;//已经知道构造函数赋值更好,这里还这么写一下~ } A & top(A& v ) /*函数原型 语法高亮后显示它并没有变成函数……(或者说和下面的定义不匹配 为什么呢)*/ { if(v.val > this->val) return v; else return *this; } const A& A::top (const A& v )const //函数定义 { if(v.val >this->val) return v; else return *this; }};int main(){A a;a.voluation();A b;b.voluation();a.top(b);//本来使用引用是为了方便后续步骤 但是我发现我不知道如何打印出 top函数返回的引用
#include <iostream>using namespace std;class A{private: int val;public: void valuation() const { cout << val; } const A & top(const A &v) const { return v.val > val ? v : *this; }};int main(){ A a, b; a.valuation(); b.valuation(); a.top(b).valuation(); // a.top(b)的结果是个A对象可以直接调用成员函数}
[解决办法]
A &ret = a.top(b);ret.valuation();
[解决办法]
你想打印一个指针是吧?
可以使用%p,使用printf,或者scanf