stri(){}
stri(char *s);//constructor used to initilize object with constant string
stri(stri &s1);//copy constructor performs memberwise copy
friend stri operator+(stri &s1,stri &s2);//conccats two string objects
void operator=(stri &s);//performs memberwise copy
//In main
//s1 and s2 are initilized with constant strings
stri s3=s1+s2; //Gives error? However when copy constructor is removed works fine
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You declared the copy constructor like this:
This line, specifically the expression on the right hand side of
=
, produces a temporary:As this is copy initialization, it needs to call the copy constructor. But as temporaries cannot bind to references to non-const objects, you get an error.
When you comment out the copy constructor, the compiler generates one for you. Its signature is then
Now it takes a reference to const and a temporary can bind to it. The fix should be obvious now.
Note that even though a well formed copy initialization requires an accesible copy constructor, the compiler can choose to elide the call to it during optimization, even when that elision changes the observable behavior of your program.
Let me dust off my crystal ball and guess that the error you're getting is somewhere along the lines of "temporary cannot bind to reference." That's because your copy constructor takes its parameter as
stri &
instead ofconst stri &
; in other words, a reference to non-const. Such references cannot bind to temporaries.s1 + s2
returns a temporary, so the copy ctor invocation fails.Unless you're doing really whacky stuff in your copy ctor (modifying the object copied from), change it to take its parameter as
const stri &
.