注册 登录
编程论坛 C++教室

理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。

yang158 发布于 2019-04-02 23:46, 3795 次点击

#include <iostream>
using namespace std;
class CPoint
{
public:
    void Set(int x,int y);
    void Print();
private:
    int x;
    int y;
};

void CPoint::Set(int x,int y)
{
    x = x;
    y = y;
}
void CPoint::Print()
{
    cout<<"x="<<x<<",y="<<y<<endl;
}

void main()
{
    CPoint pt;
    pt.Set(10,20);
    pt.Print();
}
问题一:以上程序编译能通过吗,试解释该程序?
答:
问题二:以上程序的运行结构是否正确,如果不正确,试分析为什么,应该如何改正?
答:
3 回复
#2
ZJYTY2019-04-03 09:05
你没有试着运行一下吗?
#3
yang1582019-04-04 00:03
回复 2楼 ZJYTY
运行了啊,结果不对啊
所以要修改
#4
rjsp2019-04-04 08:42
回复 3楼 yang158
既然运行过了,那为什么还问:
问题一:以上程序编译能通过吗,试解释该程序?

问题二:以上程序的运行结构是否正确?
你只需要问“应该如何改正?”即可。


    x = x;
    y = y;
你不觉得这代码很奇怪?改为
this->x = x;
this->y = y;
试试吧。


另外,整个代码看起来非常外行,一看就知道属于“附魔外道”:
a. 没有构造函数,那 x,y 怎么初始化?也就是定义后,Set之前,其实属于不可使用的状态。
b. Print函数?为什么不一致性的使用C++流?
c. Print函数好歹也加个 const 呀,否则 const CPoint 对象怎么调用 Print ?
程序代码:
#include <iostream>

class CPoint
{
public:
    CPoint();
    CPoint( int x, int y );
private:
    int x_, y_;

    friend std::ostream& operator<<( std::ostream& os, const CPoint& pt );
};

CPoint::CPoint() : x_(0), y_(0)
{
}
CPoint::CPoint( int x, int y ) : x_(x), y_(y)
{
}
std::ostream& operator<<( std::ostream& os, const CPoint& pt )
{
    return os << '(' << pt.x_ << ',' << pt.y_ << ')';
}

using namespace std;

int main( void )
{
    CPoint pt( 10, 20 );
    cout << pt << endl;

    pt = CPoint( 30, 40 );
    cout << pt << endl;

    return 0;
}
因为你使用的是远古时期的VC6,所以我没加“noexcept”修饰,它不认识。
如果你使用现代人所使用的C++编译器,记得加上noexcept。


1