c ++必须只使用一个参数

时间:2017-05-30 11:19:20

标签: c++ forms c++11

我是一个新的c ++学习者。现在,我的代码中存在问题,但我不知道如何调试它。请帮我。它是form.h文件。 我尝试移动val和运算符<<进入表格。

class Form{
friend ostream& operator << (ostream&, const Form&);
int prc;
int fmt;
double val;
public:
explicit Form(int p=6):prc(p){
  fmt = 0;
  wdt = 0;
}
Form& scientific(){
 fmt = ios_base::scientific;
 return *this;
 }
Form& precision(int p){
 prc = p;
 return *this;
}
Form& fill(char);
std::ostream& operator<<(std::ostream& os, const Form& bf){
  ostringstream s;
  s.precision(bf.prc);
  s.setf(static_cast<ios_base::fmtflags>(bf.fmt), ios_base::floatfield);
  s.setf(bf.fmt,ios_base::floatfield);

  s << bf.val;
 return os << s.str() ;
 }
};

这是我的main.cpp:

Form gen4(4); // general format, precision is 4
void f(double d)
{
  Form sci8 = gen4;
  sci8.scientific().precision(8);
  Form fix8 = gen4;
  fix8.fixed().precision(8); 
  cout << d << sci8(d) << fix8(d) << d;
 }

当我编译时,它说:

error: ‘std::ostream& Form::operator<<(std::ostream&, const Form&)’ must take 
exactly one argument

error: no match for call to ‘(Form) (double&)’
<< "gen4 = " << gen4(d) << endl

2 个答案:

答案 0 :(得分:1)

尝试

// vvvvvv
   friend std::ostream& operator<<(std::ostream& os, const Form& bf)
// ^^^^^^
    {
      ostringstream s;
      // ...

实施运营商。

如果您忘记了班级中的friend关键字,operator<< (std::ostream &, Form const &)Form的成员,<<左侧的参数是隐式的Form对象和两个声明的参数都在右侧。

答案 1 :(得分:0)

错误:'std :: ostream&amp; Form :: operator&lt;&lt;(std :: ostream&amp;,const Form&amp;)'必须采取 只有一个参数

以下是定义朋友功能的两种方法:

课堂内:

#include <iostream>
#include <map>
#include <functional>
#include <vector>


class C { 
    public:
        bool f(const std::vector<std::string>& s) {
            std::cout << "F" << std::endl;
            for (auto& i : s) {
                std::cout << i << std::endl;
            }
            return true;
        }

        bool g(const std::vector<std::string>& s) {
            std::cout << "G" << std::endl;
            for (auto& i : s) {
                std::cout << i << std::endl;
            }
            return true;
        }

        bool h(const std::vector<std::string>& s) {
            std::cout << "H" << std::endl;
            for (auto& i : s) {
                std::cout << i << std::endl;
            }
            return true;
        }

        std::map<std::string, std::function<bool(const std::vector<std::string>&)> >  funcMap {
            {"A", f},
            {"B", g},
            {"C", h}
        };
};


int main() {
    std::vector<std::string> v{"mno", "pqr", "stu"};
    C c;
    c.funcMap["A"](v);
}

课外:

class Form
{
    friend ostream& operator << (std::ostream& os, const Form& bf)
    {
        // do something
    }
};

错误:无法拨打'(表格)(双&amp;)' &LT;&LT; “gen4 =”&lt;&lt; gen4(d)&lt;&lt; ENDL

使用运算符重载,类似这样的

class Form        
{
    friend ostream& operator << (std::ostream& os, const Form& bf);
};


ostream& operator << (std::ostream& os, const Form& bf)
{
    //do something
}