gpt4 book ai didi

C++:构造函数问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:26 26 4
gpt4 key购买 nike

我正在尝试自学 C++,并且正在进行有关构造函数的基本练习。我有一个程序运行异常:

分数.h:

#include <iostream>

#ifndef FRACTION_H
#define FRACTION_H

using namespace std;

class Fraction
{
private:
int num;
int denom;
static int gcd(int a, int b);
void reduce();
public:
Fraction(int n=0, int d=1);
Fraction(Fraction& f);
~Fraction();

Fraction& operator=(const Fraction& f);

friend Fraction operator+(const Fraction& f1, const Fraction& f2);

friend ostream& operator<<(ostream& out, const Fraction& f);
};

#endif // FRACTION_H

Fraction.cpp(省略了一些实现):

#include "../include/Fraction.h"

#include <cassert>
#include <iostream>

using namespace std;

int Fraction::gcd(int a, int b) {
// implementation omitted
}

void Fraction::reduce() {
// implementation omitted
// this just reduces fractions to lowest terms, like 3/6 to 1/2
}

Fraction::Fraction(int n, int d) {
cout << "new fraction, n=" << n << ", d=" << d << endl;
assert(d != 0);
if (d < 0) {
num = -n;
denom = -d;
} else {
num = n;
denom = d;
}
reduce();
}

Fraction::Fraction(Fraction& f) {
cout << "copy fraction " << f << " at " << &f << endl;
num = f.num;
denom = f.denom;
}

Fraction::~Fraction() {
}

Fraction& Fraction::operator=(const Fraction& f) {
cout << "assign fraction to " << f << " at " << &f << endl;
if (this == &f)
return *this;
num = f.num;
denom = f.denom;
return *this;
}

Fraction operator+(const Fraction& f1, const Fraction& f2) {
cout << "adding " << f1 << " and " << f2 << endl;
return Fraction(f1.num * f2.denom + f2.num * f1.denom,
f1.denom * f2.denom);
}

ostream& operator<<(ostream& out, const Fraction& f) {
out << f.num << "/" << f.denom;
return out;
}

主要.cpp:

#include "include/Fraction.h"

#include <iostream>

using namespace std;

int main()
{
Fraction f1(1, 3);
Fraction f2(1, 2);
cout << f1 << endl;
cout << f2 << endl;
cout << (f1 + f2) << endl;
return 0;
}

当我运行它时,前两个打印语句按预期输出 1/31/2,但第三个输出 0/1 而不是 5/6。根据我的调试语句,我通过 Fraction(int, int) 构造函数创建了 5/6,但出于某种原因,它随后被调用为 0/1。当我删除复制构造函数时,代码打印出 5/6。这是怎么回事,如何在不删除复制构造函数的情况下修复它?

最佳答案

复制构造函数的签名应该是

Fraction(const Fraction&);

不是

Fraction(Fraction&);

当您执行 return Fraction(...); 时,编译器必须调用 Fraction(const Fraction&),因为返回的分数是临时的,但由于你没有定义它,你的编译器让一些奇怪的事情发生了。你的编译器表现得很奇怪,允许你以某种方式使用默认构造函数,当它应该踢出一个错误时。在 gcc 上按原样编译代码不起作用,您必须进行我提到的修改,这应该可以修复它。

此外,您的编译器没有在该函数上使用 RVO 的事实暗示您使用的是非常老旧和/或糟糕的编译器。

关于C++:构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067462/

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