【问题标题】:Reference return type of member functions to custom classes in C++将成员函数的返回类型引用到 C++ 中的自定义类
【发布时间】:2020-04-09 11:26:24
【问题描述】:

我有以下代码:

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std ; 

class abc{
public :
    string name;
    abc & change_name(string s);
};

abc & abc::change_name(string s) {
    this->name = s;
    return *this;
};

int main(){
    abc obj1 ;
    abc temp ; 
    temp = obj1.change_name("abhi");

cout<<"Name is : "<<obj1.name<<endl; \\Prints - Name is : abhi
cout<<"Name is : "<<temp.name<<endl;  \\Prints -Name is : abhi
\\cout<<"Name is  "<<temp->name<<endl;  \\\\Error : base operand of '->' has non-pointer type 'abc'.
    return 0;
}

abc 类的成员函数change_name(string s) 返回一个abc 类型的指针。在 main 里面,我有一个abc 类型的temp 对象,它不是一个指针。我的问题是语句temp = obj1.change_name("abhi") 是如何工作的,当change_name(string s) 的返回类型是一个指针但temp是不是指针本身?

【问题讨论】:

  • abc::change_name() 返回一个引用,而不是一个指针。
  • 已更正。谢谢。

标签: c++ class pointers reference


【解决方案1】:

这个函数

abc & abc::change_name(string s) {
    this->name = s;
    return *this;
};

不返回指针。它返回对当前对象的引用。

所以在这个声明中

temp = obj1.change_name("abhi");

这里使用了默认的复制赋值运算符。其实这个语句等价于

temp = obj1;

您可以将一个对象的引用视为它的、对象、别名。

返回指针的函数可能如下所示

abc * abc::change_name(string s) {
    this->name = s;
    return this;
};

将您的原始程序与这个经过轻微更新的程序进行比较

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std ; 

class abc{
public :
    string name;
    abc * change_name(string s);
};

abc * abc::change_name(string s) {
    this->name = s;
    return this;
};

int main(){
    abc obj1 ;
    abc *temp ; 
    temp = obj1.change_name("abhi");

    cout<<"Name is  "<<temp->name<<endl; 

    return 0;
}

【讨论】:

  • 我怀疑 OP 没有意识到 temp = obj1 是深层副本而不是指针/引用副本,因为大多数语言都是通过引用复制的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多