没有匹配的调用函数

No matching Function for a call

我在代码块中创建了非常简单的 C++ 项目。我有头文件(CVector.h)、源文件(CVector.cpp)和主要代码(code.cpp)。当我尝试编译代码时,我收到以下消息:

CVector.cpp|22|error: no matching function for call to 'CVector::CVector()'|

code.cpp

#include <iostream>
#include "CVector.h"
using namespace std;

int main () {
CVector vec1(1,2);
CVector vec2 (3,4);
cout << "vec1 data "; vec1.printData();
cout << "vec2 data "; vec2.printData();

cout << "vec1 area: " << vec1.area() << endl;
cout << "vec2 area: " << vec2.area() << endl;

return 0;
}

CVector.h

#ifndef CVECTOR_H
#define CVECTOR_H


class CVector
{
   int x,y;
   public:
        CVector (int, int);
        int area();
        void printData ();
        CVector operator+ (CVector param );
};

#endif // CVECTOR_H

CVector.cpp

#include <iostream>
#include "CVector.h"
using namespace std;

CVector::CVector (int a, int b) {
x=a;
y=b;
}

int CVector::area() {return x*y;}

void CVector::printData(){
cout << "X = " << x << ", Y = " << y << endl;
}

CVector CVector::operator+ (CVector param )
{
    CVector temp;
    temp.x=x + param.x;
    temp.y=y + param.y;
    return temp;
}

该错误与运算符重载函数有关,因为我注释该函数时编译没有问题。

operator+中,行

CVector temp;

需要默认构造函数,但您没有定义。
(如果你定义了一个非默认构造函数,编译器将不会提供默认构造函数。)

您可以定义默认构造函数,如果您可以决定成员的合适默认值,或者您可以编写

CVector CVector::operator+ (CVector param )
{
    CVector temp(x + param.x, y + param.y);
    return temp;
}

甚至

CVector CVector::operator+ (CVector param )
{
    return CVector(x + param.x, y + param.y);
}

operator +的问题是这一行:

CVector temp;

这行创建一个默认构造的 CVector。但是,您的 CVector class 没有默认构造函数,因此出现错误。您需要在 class:

中添加一个
class CVector
{
   int x,y;
   public:
      CVector(); // Added
      //The rest as before
};

有两种实现方式。一:

CVector::CVector() {}

这将导致成员 xy 保持未初始化状态。

两个:

CVector::CVector() : x(0), y(0) {}

这会将 xy 初始化为 0。

第二个更安全,第一个更快。使用哪一个取决于您 class.

的目标

无关,但在你的双参数构造函数中,你也应该使用成员初始化列表而不是赋值:

CVector::CVector(int a, int b) : x(a), y(b) {}

对于int之类的原始类型来说,这并不重要,但这是一个成长的好习惯。它对于具有非平凡默认构造函数的类型的成员更有效,并且实际上对于没有默认构造函数的类型的成员是必要的。