C ++没有匹配的调用函数

时间:2016-01-10 11:06:38

标签: c++ class

我有错误:没有匹配函数来调用'Goo :: Goo()'

这个问题经常发生,有些人可以解释一下我在哪里犯错误。我怎么能克服这个。

以下是程序代码:

#include <iostream>

using namespace std;

class Goo{
  private:
    int a[10];
    int n;

  public:
    Goo(int x){
        n=x;
    }

    Goo(const Goo &g){
        this->n=g.n;
        for(int i=0;i<g.n;i++){
            this->a[i]=g.n;
        }
    }

    Goo operator=(const Goo &g){
        this->n=g.n;
        for(int i=0;i<g.n;i++){
            this->a[i]=g.n;
        }
        return *this;
    }

    Goo operator+(const Goo &g){
        Goo goo;
        for(int i=0;i<g.n;i++){
            goo.a[i]=this->a[i]+g.a[i];
        }
        return goo;
    }

    friend istream& operator>>(istream &in,Goo &g){
        in>>g.n;
        for(int i=0;i<g.n;i++){
            in>>g.a[i];
        }
        return in;
    }

    friend ostream& operator<<(ostream &out,Goo &g){
        for(int i=0;i<g.n;i++){
            out<<g.a[i]<<" ";
        }
        return out;
    }
};

int main()
{
   Goo A,B;

   cin>>A>>B;

   Goo C=A+B;

   cout<<C;
   return 0;
}

1 个答案:

答案 0 :(得分:3)

定义自定义构造函数(在other reasons中)时,该类不再具有默认构造函数:

struct Foo {
    int x;
};
Foo foo;  // OK

struct Foo {
    int x;
    Foo(int x_) : x{x_} { }
};
Foo foo;  // error

您可以通过添加自定义默认构造函数来解决此问题:

struct Foo {
    int x;
    Foo() { }
    Foo(int x_) : x{x_} { }
};

或至少有一个包含所有默认参数的构造函数:

struct Foo {
    int x;
    Foo(int x_ = 0) : x{x_} { }
};

从C ++ 11开始,您还可以强制编译器发出默认构造函数:

struct Foo {
    int x;
    Foo() = default;
    Foo(int x_ = 0) : x{x_} { }
};
相关问题