gpt4 book ai didi

c++ - 函数调用运算符的继承和重载

转载 作者:太空狗 更新时间:2023-10-29 20:13:28 32 4
gpt4 key购买 nike

我在尝试从父结构继承函数调用运算符时遇到问题。我创建了一个简单的代码来说明我的问题:

#include <iostream>
using namespace std;

template <class T, int N>
struct array
{
T value[N];
T& operator() (int);
};

template <class T, int N>
T& array<T,N>::operator() (int i)
{ return value[i]; }

template <class T, int N>
struct matrix: public array<T,N*N>
{
T& operator() (int,int);
};

template <class T, int N>
T& matrix<T,N>::operator() (int i, int j)
{ return this->value[i*N+j]; }

int main()
{
matrix<double,100> a;
a(0) = 3.5;
cout << a(0) << endl;
return 0;
};

我希望“矩阵”类从“数组”类继承 operator(),并用本地 operator() 重载它;我希望这是因为参数的数量不同。但是,此代码的编译失败并显示诸如“错误:对‘(matrix) (int)’的调用不匹配”和“注意:候选人需要 2 个参数,提供 1 个”之类的消息。如果 operator() 未在类“矩阵”中定义,则继承正常发生并且代码编译和运行正常,如预期的那样。

我做错了什么?我不想不必要地重新定义 operator()...

最佳答案

名称查找在 C++ 中的工作方式是,编译器一旦找到名称,就会停止查找。换句话说,编译器首先在 matrix 中找到 operator() 并停止查找,永远不会在 array 中找到它。

您可以使用 using 声明显式地将基础 operator() 引入作用域:

template <...>
struct matrix : public array<...> {
using array::operator();
T& operator ()(int, int);
}

关于c++ - 函数调用运算符的继承和重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21168635/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com