簡體   English   中英

將成員函數的返回類型引用到 C++ 中的自定義類

[英]Reference return type of member functions to custom classes in C++

我有以下代碼:

#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 & 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM