简体   繁体   中英

Using an object from a class as an object for another class c++

I'm writing a C++ program and I have to use an instance of a class as private member of another class. The code for the class I need to use as a member instance is the as follow:

class Triangle
{
    public:
        Triangle(int _height, int _base){ set(_height, _base); } 
        //constructor
        void set(int _height, int _base){ height = _height; base = _base; }
        int area(){ return ((height*base)/2); }
        int perimeter(){ return (2*(sqrt(((base/2)*(base/2)) +. (height*height))) + base); }
    private:
        int height; 
        int base; 
 };

And here is the definition for the class that will use the above instance as private member:

Class Penta
{
    Public:
        Penta(int b );
        Penta(){ TriPart.set(10, 10); }
    Private:
        Triangle TriPart;
};

When I compile the above code compilation fails with the following error:

error: no matching function for call to 'Triangle::Triangle()'

I really appreciate if you can help me with this.

There are several problems in the code. But that can be fixed easily.

If you would compile your code, then the compiler would already tell you, whats wrong.

So, in the first part of the code, in the calculation of the perimeter, there is a "." after the "+". Additionally you want to be careful. You are creating double values in your calculation and then return in integer. That will not work.

In your second definition, the words Class, Public and Private are capitalized. You need to use the correct keywords. Your Penta(int b) constructor has no body. And the class has also not a data member, where you could assign it,

Then, as the compiler reports, your Triangle class has no default constructor, like Triangle(){} . The default constructor of Penta needs to call some constructor of Triangle, but there is none.

There are several possible solutions:

  • Add a default constructor to class Triangle Triangle(){}
  • Modify the default constructor of the Penta class to: Penta() : TriPart(10,10) {}

I additionally recommend to initialize all variables, like

int height{ 0 };
int base{ 0 };

And last but not least, I recommend to read a good C++ book about classes and their constructors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM