简体   繁体   English

我在使用面向 object 的编程时遇到问题

[英]I'm having problems with object oriented programming

I'm having problem in my programming classes, basically we're learning about object oriented programming and I'm building a program, this is a part of the code:我的编程课有问题,基本上我们正在学习面向 object 的编程,我正在构建一个程序,这是代码的一部分:

float Pedido::calculaTotal() const {
    std::list<Produto*>::const_iterator it;
    float valorTotal;
    for (it = m_produtos.begin(); it != m_produtos.end(); ++it){
        int quantidade = it->getQtd();
        float valor = it->getValor();
        valorTotal += quantidade * valor;
    }
  return 0;
}

I"m getting this error:我收到此错误:


pedido.cpp: In member function 'float Pedido::calculaTotal() const': pedido.cpp:20:30: error: request for member 'getQtd' in '* it.std::_List_const_iterator<Produto*>::operator->()', which is of pointer type 'Produto* const' (maybe you meant to use '->'?) int quantidade = it->getQtd(); pedido.cpp: 在成员 function 'float Pedido::calculaTotal() const': pedido.cpp:20:30: error: request for member 'getQtd' in '* it.std::_List_const_iterator<Produto*>::operator ->()',它是指针类型'Produto* const'(也许你的意思是使用'->'?) int quantidade = it->getQtd(); ^~~~~~ ^~~~~~

pedido.cpp:21:27: error: request for member 'getValor' in '* it.std::_List_const_iterator<Produto*>::operator->()', which is of pointer type 'Produto* const' (maybe you meant to use '->'?) float valor = it->getValor(); pedido.cpp:21:27: 错误:在 '* it.std::_List_const_iterator<Produto*>::operator->()' 中请求成员 'getValor',它是指针类型 'Produto* const'(也许你的意思是使用'->'?) float valor = it->getValor();


Tudo bem Fabricio? Tudo bem Fabricio? Your program is almost correct, you just need a couple of corrections.您的程序几乎是正确的,您只需要进行一些更正。 You need to initialize total to zero and then return it in the end.您需要将 total 初始化为零,然后最后将其返回。

float Pedido::calculaTotal() const {
    std::list<Produto*>::const_iterator it;
    float valorTotal = 0;
    for (it = m_produtos.begin(); it != m_produtos.end(); ++it){
        Produto* p = *it;
        int quantidade = p->getQtd();
        float valor = p->getValor();
        valorTotal += quantidade * valor;
    }
  return valorTotal;
}

Also the iterator is a "pointer" itself so *it has the type of Produto* and to get the actual Produto object you need to dereference twice with either (*it)-> or alternatively do what I did above, get the pointer with Produto* p = *it;此外,迭代器本身就是一个“指针”,因此*it具有 Produto Produto*的类型,要获得实际的Produto object,您需要使用(*it)->取消引用两次,或者执行我上面所做的操作,获取指针Produto* p = *it; then use the actual pointer with p-> .然后将实际指针与p->一起使用。

Alternatively you can also use ranges like this:或者,您也可以使用这样的范围:

float Pedido::calculaTotal() const {
    float valorTotal = 0;
    for ( Produto* p : m_produtos ) {
        valorTotal += p->getQtd() * p->getValor();
    }
    return valorTotal;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM