Configuring the Constructor

Asked 2 years ago, Updated 2 years ago, 28 views

structure point{
    intx;inty;
    point(inta, intb){
        x = a;
        y = b;
    }
};
class circle {
public:
    point p;
    double;
    circuit(point a, double b){
        p = a;
        r = b;
    }
    // circle (point a, double b): p(a), r(b){ }; // no error
};
int main() {
    point p1(2,7);
    circuit c(p1,0.3);
    cout<<c.p.x<<c.p.y<<endl;
    return 0;
}

Question: The constructor part of the circuit displays the error "Compliant constructor for class point does not exist".Why should I have created two constructors for the point argument?

c++

2022-09-30 15:36

2 Answers

The constructor initializes all class members before the processing in {...} begins.
Constructors in this circle class do not describe how to initialize members (: or later)
Therefore, initialize with the "default" initialization method for each member.
The default initialization method for classes and structures is constructor invocation without arguments.
However, circle defines two constructors as indicated in the other answer, so
Constructors without arguments are not implicitly defined.

That's why I think it's a compilation error for your question.
To avoid errors, you may want to use one of the following methods:

"Also, the ""p=a"" part of the original code is a substitution operator (operator=())."
Yes, it is implicitly generated as "show copy", so
what the pointer is pointing to. If you want to copy, you must define an assign operator to "deep copy" yourself.


2022-09-30 15:36

Constructors of this shape

circle(point a, double b){
    p = a;
    r = b;
}

calls a constructor (=default constructor) without arguments for each parent class and field.

If no constructors are defined in the class, constructors without arguments are automatically created.point classes do not automatically create constructors without arguments because other constructors (point(int, int)) were defined.


2022-09-30 15:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.