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

新手求教~下面这一小段代码错在哪里?

ellie78 发布于 2011-05-27 04:23, 385 次点击
编写了一个名为Crest的类,我想在类外获取Crest的信息。
代码如下:
#include<iostream>
#include<math.h>

using namespace std;

class Crect
{
private:
    int left,right,top,bottom;
public:
    void GetData(int Left,int Right,int Top,int Bottom)
    {
        left = Left;
        right = Right;
        top = Top;
        bottom = Bottom;
    }

    int GetArea()
    {
        return (right-left)*(top-bottom);
    }

    ~Crect()
    {
    }
};

int main()
{
    Crect a;
    int l;
    a.GetData(1,6,8,2);
    l = a.GetData(1,6,8,2);---------------------------A处
    cout<<"left="<<l<<endl;---------------------------B处

    cout<<"The area is: "<<a.GetArea()<<endl;
}
以上。
成员函数GetData设定了矩形的坐标,我想获得left值并将其打印输出。为便于表述,我把有问题的代码标为AB两处。我知道肯定有错,但不太能理解错在何处,该怎么改进?

谢谢~~~~~~~
6 回复
#2
wavewind2011-05-27 07:48
void GetData(int Left,int Right,int Top,int Bottom)
    {
        left = Left;
        right = Right;
        top = Top;
        bottom = Bottom;
    }

这是一个没有返回值得函数,可以这样理解:c++中函数的传递在没有采取传地址的方式的时候,是采用传值的方式进行的,你这个函数就是传值方式。
那么如果你要在返回值中获取left的值,建议采用以下格式:
int GetData(int Left,int Right,int Top,int Bottom)
    {
        left = Left;
        right = Right;
        top = Top;
        bottom = Bottom;
        return left;
    }
那么你在调用int l; l=a.GetData(1,6,8,2);
的时候可以获取相应的值!


但是总体来说,这个程序是个失败的程序,建议像这种情况,完全可以采用类的构造函数重载进行,而在主函数中直接定义对象,获取相关成员值,当然在private的成员数据类外调用时,采用共有成员函数的方式!

#3
ellie782011-05-27 09:46
楼上的大侠请留步~~~
你提供的解决方法很赞~
但是,我又节外生枝地想了下:如果我想将left,right,top,bottom的值依次全调用并打印出来,怎么改比较好?
我知道再添成员函数
int ReadLeft()
{
return left;
}

int ReadRight()
{
return right;
}

int ReadTop()
{
return top;
}

int ReadBottom()
{
return bottom;
}
应该可行,但是有更好的办法吗?
#4
Toomj2011-05-27 11:05
在类体中声明友元函数:friend void display(Crect &);

void display(Crect &d)
{
    cout<<d.left<<"/"<<d.right<<"/"<<d.top<<"/"<<d.bottom<<endl;
}
#5
lianjiecuowu2011-05-27 11:07
#include<iostream>
#include<math.h>          //这里可以用<cmath>代替啊,.h不是标准的,这是细节上的,没错啊

using namespace std;

class Crect
{
private:
    int left,right,top,bottom;
public:
    void GetData(int Left,int Right,int Top,int Bottom)
    {
        left = Left;
        right = Right;
        top = Top;
        bottom = Bottom;
    }

    int GetArea()
    {
        return (right-left)*(top-bottom);
    }

    ~Crect()
    {
    }
};

int main()
{
    Crect a;
    int l;
    a.GetData(1,6,8,2);                                                   //无需l,调用getarea()函数就行;直接输出啊
    l = a.GetData(1,6,8,2);---------------------------A处
    cout<<"left="<<l<<endl;---------------------------B处              //输出left,直接使用a.left就行啦

    cout<<"The area is: "<<a.GetArea()<<endl;                    定义的int main(0应当有返回值啊,return 0;
}


细节决定成败啊
#6
ellie782011-05-27 11:42
以下是引用Toomj在2011-5-27 11:05:15的发言:

在类体中声明友元函数:friend void display(Crect &);

void display(Crect &d)
{
    cout<<d.left<<"/"<<d.right<<"/"<<d.top<<"/"<<d.bottom<<endl;
}


谢谢少侠~~
#7
ellie782011-05-27 11:43
回复 5楼 lianjiecuowu
呵呵,谢谢~~
1