简体   繁体   English

将一个类中的对象用作另一个类的对象C ++

[英]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. 我正在编写C ++程序,并且必须使用一个类的实例作为另一个类的私有成员。 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. 您的Penta(int b)构造函数没有正文。 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(){} . 然后,如编译器所报告的那样,您的Triangle类没有默认构造函数,例如Triangle(){} The default constructor of Penta needs to call some constructor of Triangle, but there is none. Penta的默认构造函数需要调用Triangle的某些构造函数,但是没有。

There are several possible solutions: 有几种可能的解决方案:

  • Add a default constructor to class Triangle Triangle(){} 向类Triangle Triangle(){}添加默认构造函数
  • Modify the default constructor of the Penta class to: Penta() : TriPart(10,10) {} 修改Penta类的默认构造函数为: 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. 最后但并非最不重要的一点是,我建议读一本关于类及其构造函数的不错的C ++书。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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