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

在c++类中怎么写一个返回值是自身非引用类型的成员函数

蓝天绿水 发布于 2018-03-11 18:51, 2369 次点击
class test
{
    char *name;
public:
    test fun(test const &other);//这个函数怎么写 我想将other中的name的值传递给当前调用的对象,其他的方式我会写,但是这个函数的实现应该怎么写
};
4 回复
#2
Jonny02012018-03-12 18:47
test func(test const &other) {
    this->name = other.name;
    return *this;
}
#3
蓝天绿水2018-03-13 20:38
嗯嗯,明白了
那如果写成友元函数应该怎么实现呢?
friend test fun(test const &other);
#4
蓝天绿水2018-03-13 21:13
嗯嗯,明白了
 那如果写成友元函数应该怎么实现呢?
friend test fun(test const &other);
test func(test const &other)
{
     this->name = other.name;
     return *this;
}
这样写诗错的,在析构中间的临时变量时出错
但是返回值是引用类型时就是正确的,向下面这样就是OK的
friend test &fun(test const &other);
test &func(test const &other)
{
     this->name = other.name;
     return *this;
}
#5
蓝天绿水2018-03-13 21:42
我知道了,是拷贝构造函数的原因
1