Answer the question
In order to leave comments, you need to log in
How to correctly overload constructors in a class?
I ran into a problem: With such an entry as below, everything works and everything compiles fine:
#include <iostream>
using namespace std;
class A{
private:
int aa;
int ab;
public:
A():aa(0),ab(0){}
A(int a):aa(a),ab(0){}
void Show(){
cout<<"Var1: "<<aa<<endl<<"Var2: "<<ab<<endl;
}
};
int main(){
A obj = 5;
obj.Show();
return 0;
}
cannot bind non-const lvalue reference of type 'A&' to an rvalue of type 'A'
A obj = 5;
#include <iostream>
using namespace std;
class A{
private:
int aa;
int ab;
public:
A():aa(0),ab(0){}
A(int a):aa(a),ab(0){}
A(A& obj);
void Show(){
cout<<"Var1: "<<aa<<endl<<"Var2: "<<ab<<endl;
}
};
int main(){
A obj = 5;
obj.Show();
return 0;
}
Answer the question
In order to leave comments, you need to log in
Let's consider the problem in more detail.
class A {
private:
int aa;
int ab;
public:
A()
: aa(0), ab(0) {} // (4) note: candidate constructor not viable: requires
// 0 arguments, but 1 was provided
A(int a)
: aa(a), ab(0) {} // (2) note: candidate constructor not viable: no known
// conversion from 'A' to 'int' for 1st argument
A(A& obj); // (3) note: andidate constructor not viable: expects an l-value
// for 1st argument
void Show() { cout << "Var1: " << aa << endl << "Var2: " << ab << endl; }
};
int main() {
A obj = 5; // (1) error: cannot bind non-const lvalue reference of type ‘A&’
// to an rvalue of type ‘A’
obj.Show();
return 0;
}
A(A& obj);
T::T(const T&)
A(A& obj) = default;
T::T(T&)
...
A(int a) : aa(a), ab(0) {
cout << "Copy ctor with 1 parameter is called " << endl;
}
…
int main() {
…
Вывод:
Copy ctor with 1 parameter is called
Var1: 5
Var2: 0
A(A& obj); ,
A(A&& obj);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question