gpt4 book ai didi

c++ - 通过引用返回包含对象的 vector

转载 作者:行者123 更新时间:2023-12-02 10:39:26 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数返回包含n个随机分数的 vector 。我收到一个奇怪的错误,告诉我“请参见对函数模板实例化的引用,以及”类分数:没有可用的复制构造函数或将复制构造函数声明为'explicit'”。非常感谢您的帮助。

这是我编写的代码:

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

最佳答案

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

Fraction(const Fraction & other); // copy c'tor是副本构造函数。

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

关于c++ - 通过引用返回包含对象的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50693722/

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