首页 > 解决方案 > 通过引用返回包含对象的向量

问题描述

我正在尝试编写一个函数,该函数返回一个由 n 个随机分数组成的向量。我收到一个奇怪的错误,告诉我“查看对函数模板实例化的引用,并且“类 Fraction:没有可用的复制构造函数或复制构造函数被声明为'显式'”。非常感谢任何帮助。

这是我写的代码:

vector<Fraction> & genV(int n) {
    vector<Fraction> temp;
    for (int i = 0; i < n; i++) {
        int n, d;
        n = rand() % (100);
        d = rand() % (100);
        // create a new random fraction
        Fraction *tempFraction = new Fraction(n, d);
        // push new fraction to vector
        temp.push_back(*tempFraction);
    }
    return temp;
}

这是头文件:

#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Fraction {
private:
    int *numerator;
    int *denominator;
public:
    int getNumerator();
    int getDenominator();
    void reduce();
    int gcd(int, int);
    // constructors
    Fraction();  // default c'tor
    Fraction(int n); // create a fraction of n/1
    Fraction(int n, int m); //  Fraction n/m
    Fraction(Fraction & other);  // copy c'tor

    ~Fraction();  // destructor
    Fraction & operator=(Fraction & rhs);
    // overload assignment operator
    Fraction & operator+(Fraction &rhs);
    Fraction & operator-(Fraction &rhs);  // overload binary operator -
    Fraction & operator-();  // overload unary operator -   (negative)
    Fraction & operator *(Fraction &rhs);
    Fraction & operator/(Fraction & rhs);

    Fraction & operator++();// overload prefix ++
    Fraction & operator++(int);  // overload postfix ++
    Fraction & operator--();// overload prefix --
    Fraction & operator--(int);  // overload postfix --

                                 //  overload relational operators
    bool operator >(Fraction & rhs); // return true if *this > rhs , false elsewise
    bool operator == (Fraction & rhs);
    bool operator < (Fraction & rhs);
    bool operator !=(Fraction &rhs);

    Fraction & operator+=(Fraction & rhs);
    Fraction & operator-=(Fraction & rhs);
    Fraction & operator*=(Fraction & rhs);
    Fraction & operator/=(Fraction & rhs);

    string toString();
    char * toCstring();
    bool isZero();  // return true if *this is zero

    int power(int base, int exp);
    Fraction & operator^(int n);

    friend istream & operator >> (istream & in, Fraction & rhs);
    friend ostream & operator << (ostream & out, Fraction & rhs);

};
#endif

标签: c++stdvector

解决方案


Fraction(Fraction & other); // copy c'tor不是复制构造函数。

Fraction(const Fraction & other); // copy c'tor是一个复制构造函数。

而您没有获得默认值的原因是因为您使用其他声明禁用了它的自动生成。


推荐阅读