c++ - 重载返回 vector 的函数,以便它可以返回不同类型的 vector

标签 c++ vector overloading complex-numbers

<分区>

我在我的代码中多次遇到这个问题(现在,我认为没有办法绕过它):出于某种原因,当我尝试编写一个返回 std::vector<long double> 的方法时并尝试使用返回不同 std::vector 的相同方法名称重载它,比如说,std::vector<std::complex<long double> > ,我收到类似于以下内容的错误消息: std::vector<std::vector<long double> > cannot be overloaded with std::vector<long double> 即使我有必要的类(class)#include'。 这是为什么??这背后有什么道理吗??

下面是一些模拟问题的代码:

#ifndef MATRIXALGORITHMS_H
#define MATRIXALGORITHMS_H
#include <complex>
#include <vector>

class MatrixAlgorithms
{
    public:
        MatrixAlgorithms();
        //two algorithms that are not strictly for matrices; they are for solving quadratic and cubic polynomials
        //quadratic method; the roots might be real, so there should be two versions of this algorithm
        std::vector<long double> quadraticFormula(long double, long double, long double);
        std::vector<std::complex<long double> > quadraticFormula(long double, long double, long double);
    protected:
    private:
};

#endif // MATRIXALGORITHMS_H

我试图编译它,但它给了我上述错误....

最佳答案

方法的返回类型不用于重载决议。

为什么?原因有很多,但最简单的是因为当返回值被忽略时,您将无法猜测调用了哪个函数,这是完全合法的。

例如:

int f();
double f();


f(); // Which one would you call ?

其他更复杂的原因很容易找到:

int f();
double f();

void g(int);
void g(double);

g(f()); // Which f and g do you call ?

更不用说auto等等...

关于c++ - 重载返回 vector 的函数,以便它可以返回不同类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873870/

相关文章:

C++11:参数包扩展计数器

c++ - 用 vector 中的数字进行操作

c++ - OpenGL 中的视觉糖果

c++ - 在没有 DirectX 的情况下在 Windows 上获得精确的屏幕刷新率?

c++ - 下限误差

c++ - 将派生类存储到 vector C++

c++ - 如何重载 std::cout << std::endl?

c++ - 该 vector 按哪个值排序?

C#函数重载规则

c++ - 关于函数重载的查询