成员的C ++请求,属于非类型

时间:2013-01-17 23:30:49

标签: c++

我有一个简单的程序。主要由我的教授提供。我们要编写名为entersimplifydisplay的3个函数。

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

struct Fraction {
    int numerator;
    int denominator;
};

void enter(struct Fraction* fraction);
void simplify(struct Fraction* fraction);
void display(struct Fraction fraction);

int main() 
{
    struct Fraction fraction;
    cout << "Fraction Simplifier" << endl;
    cout << "===================" << endl;
    enter(&fraction);
    //simplify(&fraction);
    //display(fraction);
}

void enter(struct Fraction* fraction) {
    cout << "Numerator:     " << endl;
    cin >> *fraction.numerator; // the line that doesn't work, line 31
}

void simplify(struct Fraction* fraction) {}
void display(struct Fraction fraction) {}

错误:

w2.cpp:31:19: error: request for member ânumeratorâ in âfractionâ, which is of non-class type âFraction*â

有问题的行

void enter(struct Fraction* fraction) {
    cout << "Numerator:     " << endl;
    cin >> *fraction.numerator; // the line that doesn't work, line 31
}

4 个答案:

答案 0 :(得分:4)

您有操作订单问题。你想要:

cin >> (*fraction).numerator

或更具惯用性:

cin >> fraction->numerator;

答案 1 :(得分:3)

您遇到operator precedence问题。这个表达

*fraction.numerator;

被解析为

*(fraction.numerator);

试试这个

(*fraction).numerator;

或者

fraction->numerator;

答案 2 :(得分:1)

您遇到运营商优先问题(* Operator. Operator),reference link

你可以尝试:

cin >> fraction->numerator;

cin >> (*fraction).numerator;

或者更好的方法是将Fraction的引用传递给entersimpilfydisplay,例如:

void enter(Fraction& fraction)
{
  cout << "Numerator:     " << endl;
  cin >> fraction.numerator;
}
void simplify(Fraction& fraction);
void display(const Fraction& fraction);

答案 3 :(得分:1)

一元operator*具有非常低的优先级,因此表达式的操作顺序将在它之前发生。要解决此问题,我们将部件包装在括号中以指定顺序:

(*fraction).number

首先取消引用fraction然后我们可以访问作为结果返回的对象。