c++ - 通过引用返回包含对象的向量
问题描述
我正在尝试编写一个函数,该函数返回一个由 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
解决方案
这Fraction(Fraction & other); // copy c'tor
不是复制构造函数。
这Fraction(const Fraction & other); // copy c'tor
是一个复制构造函数。
而您没有获得默认值的原因是因为您使用其他声明禁用了它的自动生成。
推荐阅读
- python - DataFrame:按一列分组并平均其他列
- javascript - 具有有效 access_token 的 Google Picker API 在首次使用时要求登录
- java - 如何从scala中的IF条件的else块中不返回任何内容?
- python - Django 自定义身份验证模型
- python - Python - 带有 mercure_hub 的烧瓶
- c# - 在系统启动时启动 WPF 应用程序时出错
- xcode - 在 Xcode 中使用断点时应用程序崩溃
- python - 如 guppy 所述,长期运行项目的奇怪内存消耗
- xcode - 如何在 Apple Watch 上从 xcode 运行我的应用程序?
- html - DataTables:如何将第一列(ID)显示为超链接?