Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

c++ - How to use operator= with a reference

The code bellow pertains to question Error seemingly inconsistent behaviour in overloaded operator= used in variable definition that has been answered. My question arized in the context of trying to define and initialize a reference to a structure using an integer.

So I need instead of writting "S s1=3;" I need to write "S& s1=3;" how am I going to manage it;

struct S{
    int a,b;
    void operator=(int x){a=x;b=x*x;}
    S(){};
    S(int x){a=x;b=x*x;}
};

int main(){
    S s1;s1=5;
    S s2;s2=7;
    S s3=9;
    S s4;
}

The code of main() should be modifified as follows:

int main(){
    //S s0=S{15,20};
    S s1;s1=5;
    S s2;s2=7;
    S s3=9;
    S s4;

    S& s5;s5=10;
    S& s6=10;
}

but compiling I have errors:

main.cpp:16:5: error: ‘s5’ declared as reference but not initialized

main.cpp:17:8: error: invalid initialization of non-const reference of type ‘S&’ from an rvalue of type ‘int’ ( regards s6 ).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, you are not using operator=, rather this is a copy-initialization.

That is, the expression S s1 = 3; uses non-explicit constructor S(int x) and also non-explicit and accessible copy constructor S(const S& x) (hopefully without any additional overhead).

Going further, you can't use S& s1 = 3; not because you cannot assign 3 to reference, but because the right hand side of assignment is an R-VALUE (that is, a temporary). However, you can extend its lifetime using const reference to l-value, as r-values like very much to be bound by const l-value references:

const S& s1 = 3;

This will work as long as S(int x) is not marked as explicit.

Alternatively, (you should not do that at all), you can use r-value reference:

S&& s1 = 3; // implicitly
S&& s2 = S(3); // explicitly

And the error you see trying to compile S& s5;:

main.cpp:16:5: error: ‘s5’ declared as reference but not initialized

tells you that you cannot just create a variable that is a reference (as opposed to pointers), without initializing it.

But if you had a validly initialized reference, then whenever you would use assignment, only then the operator= would be invoked:

S s1(1);
S& s1ref = s1;
S s2(2);
s1ref = s2; // s1.operator=(s2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...