【问题标题】:C++ . How to pass an object pointer into a member function within a functionC++ 。如何将对象指针传递给函数内的成员函数
【发布时间】:2023-03-28 12:10:02
【问题描述】:

对不起,如果问题本身看起来有点令人困惑,这是我的 cpp 文件的代码。

//main.cpp

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

 int unitTests(Fraction* f) {

 cout << "Fraction Simplifier Tests" << endl;
 cout << "=========================" << endl;

 // fill in code for unit tests


    int num, den;

    Fraction::set(4,16);

    cout << "Input:  " << num << "/" << den << endl;
    cout << "Output: " << num << "/" << den << endl;

 }

 int main() {
 Fraction fraction;
 bool passed;

 passed = unitTests(&fraction);

 if (passed)
     cout << "Passed All Tests" << endl;
 else
     cout << "Failed Tests" << endl;
 }

这是我的 .h 文件

class Fraction {
  int n, d;

public:
  void set(int n, int d);
  void simplify();
  void display() const;
  int numerator() const;
  int denominator() const;
};

我有另一个 .cpp 文件,用于存储我的成员函数的代码,但我对此没有任何问题,所以我不会包含它。

基本上我得到一个错误,说我不能在没有对象的情况下从 void Fraction::set(int, int) 调用成员函数。我不确定我将如何去做这件事...... 在我的困惑中,我已将行更改为 Fraction::fraction.set(4,16)。如果有人能阐明我将如何在这里使用我的分数对象,我将不胜感激。

【问题讨论】:

    标签: c++ function parameter-passing member


    【解决方案1】:

    这只是你的“调用成员函数”语法错误;剩下的代码和问题都不是重点。

    你写的时候:

    Fraction::set(4,16);
    

    你的意思是:

    f->set(4,16);
    

    还有其他问题,比如你的int num, den 没有价值,什么也不做。

    【讨论】:

    • 没关系...你是对的,非常感谢,当计时器用完时会选择正确答案
    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2012-08-01
    • 2015-03-22
    • 1970-01-01
    相关资源
    最近更新 更多