【问题标题】:C++ trouble with using a member function as an operand. error C2679将成员函数用作操作数的 C++ 问题。错误 C2679
【发布时间】:2014-04-29 01:53:22
【问题描述】:

我需要一些帮助!

这是我在任何类型的编码方面的第一门课程,并且我遇到了我的第一道主要课程,这是 C++ 课程。我的问题出现在 main.cpp 的第 19 行:

错误 C2679:二进制“=”:未找到采用“void”类型右侧操作数的运算符(或没有可接受的转换)

我的问题就是这么简单,我需要找出是什么使我的 multipliedBy 函数不能成为适用的操作数,这样我才能继续我的编程!

附带说明,如果它不正确,请不要担心我的“结果”函数,因为我仍在修改它。

感谢您的宝贵时间。

分数.cpp

#include <iostream>
#include "fraction.h"
using namespace std;

fraction::fraction()
{
    top = 0; //default constructor 
    bottom = 1;
}

fraction::fraction(int numerator, int denominator)
{
    top = numerator;
    bottom = denominator;
}

void fraction::answer()
{
    top = numAnswer;
    bottom = denAnswer;
}

void fraction::print() const
{
    cout << top << "/" << bottom; 
}

void fraction::multipliedBy(fraction f2)
{
    numAnswer = top * f2.top;
    denAnswer = bottom * f2.bottom;
}

void fraction::result(fraction answer)
{
    cout << " is ";
}

分数.h

#include <iostream>

#ifndef FRACTION_H
#define FRACTION_H
using namespace std;

class fraction {
    public:
        fraction();
        fraction(int numerator, int denominator);
        void answer();
        void print() const;
        void multipliedBy(fraction f2);
        void result(fraction answer);
    private:
        int numerator;
        int denominator;
        int top;
        int bottom; 
        int numAnswer;
        int denAnswer;
};

#endif

main.cpp

#include <iostream>
#include "fraction.h"
using namespace std;

int main()
{
    fraction f1(9,8);
    fraction f2(2,3);
    fraction result;

    cout << "The result starts off at ";
    result.print();
    cout << endl;

    cout << "The product of ";
    f1.print();
    cout << " and ";
    f2.print();
    result = f1.multipliedBy(f2);
    result.print();
    cout << endl;
}

【问题讨论】:

  • multipliedBy()void (不返回任何内容),所以说result = f1.multipliedBy(f2); 是无稽之谈。这是什么意思? result = nothing ?
  • 这是否意味着我应该将 multipliedBy 更改为布尔值?我正在学习的课程要求我保持 main.cpp 原样。
  • 如果你不能改变main,那么multipliedBy()必须返回一个fraction
  • 感谢约翰的帮助/解释。

标签: c++ class operands


【解决方案1】:

multipliedBy() 需要是这样的:

fraction fraction::multipliedBy(fraction f2)
{
    fraction theAnswer(top, bottom);
    theAnswer.top *= f2.top;
    theAnswer.bottom *= f2.bottom;
    return theAnswer;
}

您还需要更改标题。 请注意,此解决方案不会修改您正在处理的分数或f2。它只是返回一个新的fraction,其中包含答案。

您需要(至少)一条评论来解释为什么您拥有所有这些成员。似乎你只需要一个顶部和一个底部(不管你怎么称呼它们)。

  • 分子
  • 分母
  • 顶部
  • 底部
  • numAnswer
  • denAnswer

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 2014-11-08
    • 1970-01-01
    • 2016-09-11
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多