在C++中使用类时出错(与调用 Class_name 不匹配)

error in using class in C++ (no match for call to Class_name)

本文关键字:Class 调用 name 不匹配 出错 C++      更新时间:2023-10-16

当我尝试编译下面的代码时,我收到以下错误:

homework3_test.cpp:111:25: 错误:对"(PowerN) (int&)"的调用不匹配 power_three(test_power2);

PowerN 是一个类。

class PowerN{
    public:
    static int i;
    PowerN(int a);  
};

power_three定义为

功率N power_three(3);

这个很好,而"3"是一个整数。但对于以下三个整数变量:

国际test_power1、test_power2 test_power3;

它返回错误。那么它们为什么不同呢?是int test_power1没有值所以它变成int&的原因吗?我该如何解决这个问题?

下面是PowerN的代码

PowerN::PowerN(int a){
    int b=0;
    if (i>0){
        a = pow(b,(i-1));
    }
    else {
        b=a;
    }
    i= i+1;
}

更新:PowerN 需要更改它需要的第 2、3、4 个整数的值,以下是要求:

PowerN 的构造函数采用单个整数 N。每次调用 PowerN 实例的函数运算符时,它都会将其参数的值更改为 N**x,其中 x 是调用函数运算符的次数。例如:

int x;
PowerN power_three(3);
power_three(x);//x will now be 1
power_three(x);//x will now be 3
power_three(x);//x will now be 9

重现错误的代码是:

homework3_test.cpp:111:25: 错误:对"(PowerN) (int&)"的调用不匹配

power_three(test_power2);

问题出现在更新的代码中:

int x;
PowerN power_three(3);
power_three(x);//x will now be 1

最后一行尝试调用PowerN::operator() 。但是,您没有定义operator() 。错误消息有点神秘,但它说它寻找了PowerN::operator()(int &)但没有找到它。

我不知道你想象会发生什么,会导致"x 现在将是 1"。 似乎您正在尝试在已存在的对象上再次调用构造函数。 这是不合法的;即使是这样,语法也会有所不同。

也许您应该将构造函数中当前的一些代码移动到成员函数中(例如calculate(int &),然后执行以下操作:

PowerN power_three(3);
power_three.calculate(x);