【问题标题】:why i m getting [Error] no matching function for call to 'car::car()'为什么我得到 [Error] no matching function for call to 'car::car()'
【发布时间】:2021-10-24 13:56:09
【问题描述】:

我创建了具有两个成员变量 a 和 b 的 car 类的两个对象....我想创建一个新对象,其 a 和 b 是我之前创建的对象的 a 和 b 的乘积。

#include<iostream>
using namespace std;
class car
{
    private:
        int a,b;
    public:
        car(int x,int y)
        {
            a=x;
            b=y;
        }
        void showdata()
        {
            cout<<a<<" "<<b<<endl;
        }
        car add(car c)   // to multiply 'a' and 'b' of both objects and assigning to a new 
                            object 
        {
            car temp;    // new object of class car
            temp.a = a*c.a;   
            temp.b = b*c.b;
            return temp;
        }
        
};
int main()
{
    car o1(3,5);
    car o2(0,7);
    car o3;
    o3=o1.add(o2);
    o1.showdata();
    o2.showdata();
    o3.showdata();
    
}

【问题讨论】:

  • 如果错误出现在car o3; 行,那是因为构造函数需要两个参数,但没有提供。

标签: c++ oop constructor overloading operator-keyword


【解决方案1】:

查看此文档。 https://en.cppreference.com/w/cpp/language/default_constructor

因此,如果您定义另一个构造函数,则不会自动将默认构造函数添加到您的类中。你做了什么。 您必须手动添加默认构造函数。例如。

class car
{
 public:
     car() = default;
      ....

 private:
    int a = 0;
    int b = 0;
}

【讨论】:

    【解决方案2】:

    要添加到@Pepijn Kramer 的答案的另一件事是您可以执行以下操作作为替代方法

    class car
    {
     public:
    //note. The call of default constructor 
    //is now converted to the call car(a_default, b_default)
         car(int x=a_default, int b=b_default)
         {
             //whatever
         }
    .......
    ....... 
     private:
        int a = 0;
        int b = 0;
    }
    

    另请注意,此变体有一个缺点,只要您可以将car::car 称为

    Car car(10);
    

    将转换为

    Car car(10,b_default);
    

    这可能不适合您的选择。如果没有,您应该坚持使用其他变体。

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      相关资源
      最近更新 更多