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

请高手帮我写写C++函数连续调用问题

hyh111 发布于 2010-04-10 01:54, 783 次点击
++函数连续调用问题
[ 标签:函数 调用,c++,函数 ] 对于下面定义的类Test:
class Test {
private:
int a;
double b;
};
要求:
(1)为类Test的每个数据成员增加一个set函数,并使这些set函数都可以连续调用。
(2)为类Test的每一个数据成员增加一个get函数。
(3)如果要求所有的get函数都可以被连续调用,该如何编写这些函数?

[ 本帖最后由 hyh111 于 2010-4-16 17:16 编辑 ]
6 回复
#2
静夜雪2010-04-10 21:30
class Test
{
    private:
    int a;
    double b;
    public:
    void set(int x);
    void set(double y);
    int get(int i);
    double get (double j);
};
void Test::set(int x)
{
    a=i;
}
void Test::set(double y)
{
    b=y;
}
int Test::get(int i)
{
     cout<<i<<endl;  
     //return i;
}
int Test::get(double j)
{
     cout<<j<<endl;  
     //return j;
}

你看看是不是这样的!!
#3
静夜雪2010-04-10 21:50
刚才哪个冒是不行;抱歉这个我在vc中编译通过了


#include<iostream>
using namespace std;

class Test
{
    private:
    int a;
    double b;
    public:
    int set(int x);
    double set(double y);
    int get(int i);
    double get (double j);
};
int Test::set(int x)
{
    a=x;
    return a;
}
double Test::set(double y)
{
    b=y;
    return b;
}
int Test::get(int i)
{
     cout<<i<<endl;  
     return 0;
}
double Test::get(double j)
{
     cout<<j<<endl;  
     return 0;
}

int main()
{
    Test v,m;
    v.get(v.set(5));
    m.get(m.set(6.8));
    return 0;
}
#4
pangding2010-04-11 10:18
要返回 *this 一般才可以连续调用。
 
楼主说的连续调用是指这样的吧?
Test a;
a.set(5).set(5.5);
这还好理解,因为本来 set 不用返回值。所以可以通过返回对象本身来完成连续调用。
但如果要求 get 连续调用就有点奇怪了。因为人们一般调用这类函数是关心它的返值,在连续调用的过程中,其实是把返值忽略了。
也不是没有方法写,可以用传出参数解决这个问题。不过这种设计感觉就很怪了。
#5
pangding2010-04-11 10:25
程序代码:

class Test
{
public:
    Test& set (int x);
    Test& set (double y);
    Test& get (int& i) const;
    Test& get (double& j) const;

private:
    int a;
    double b;
   
};

Test& Test::set(int x)
{
    a=i;
    return *this;
}
Test& Test::set(double y)
{
    b=y;
    return *this;
}

Test& Test::get(int& i)
{
    i = a;
    return *this;
}
Test& Test::get(double& j)
{
    j = b;
    return *this;
}
#6
hyh1112010-04-12 22:54
圆柱类Column的定义
class Column
{
public:
     Column(double x,double y,double r,double h);
     ~Column();
     double area();    //求圆柱面积
     double volumn();  //求圆柱体积
private:
     double height;    //高度
     double radius;    //半径
     double x;         //底面积圆心x的坐标
     double y;         //底面积圆心y的坐标

};
要求:
(1) 实现Column中的四个成员函数;
(2)增加一个友元函数,实现从键盘读取四个double类型的数据对类Column的对象进行赋值的功能;
(3)增加一个友元函数,实现将类Column的对象输出到屏幕的功能,输出信息包括对象的基本信息以及对象的面积和体积。
编程提示:
友元函数的声明:
void friend set(Column &t);
void friend print(Column &t);

[ 本帖最后由 hyh111 于 2010-4-16 17:15 编辑 ]
#7
pangding2010-04-17 10:40
你干嘛不新开一个帖子?而且这像是求作业的样子……
1