簡體   English   中英

C ++。 如何將對象指針傳遞給函數內的成員函數

[英]C++ . How to pass an object pointer into a member function within a function

抱歉,問題本身似乎有點令人困惑,這是我的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)。 如果有人能闡明我將如何使用這里的小數對象,將不勝感激。

只是您的“調用成員函數”語法是錯誤的; 剩下的代碼和問題就不重要了。

當你寫:

Fraction::set(4,16);

你的意思是:

f->set(4,16);

還有其他問題,例如您的int num, den沒有值並且什么也不做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM