【问题标题】:Instantiating class in member call在成员调用中实例化类
【发布时间】:2012-08-21 11:51:36
【问题描述】:

我有一个成员函数定义为:

void printSomeData(std::ostream& str) const;

当我尝试以这种方式从另一个类中调用该成员时:

myclass.printSomeData(std::ofstream("foo.txt"));

我收到以下错误:

错误:没有匹配的调用函数 ‘myclass::printSomeData(std::ofstream)’

注意:来自‘std::ofstream {aka 的参数 1 没有已知的转换 std::basic_ofstream}’ 到 ‘std::ostream& {aka std::basic_ostream&}'

但是,如果我像下面这样首先调用函数来实例化 ofstream,我不会收到任何错误,我不太明白:

std::ofstream foo("foo.txt");
myclass.printSomeData(foo);

谁能给我一个线索?

谢谢

【问题讨论】:

    标签: c++ oop


    【解决方案1】:

    您不能将临时对象绑定到非常量引用,您在此处执行此操作:

    myclass.printSomeData(std::ofstream("foo.txt"));
                                ^ temporary std::ostream object
    

    什么时候可以这样做:

    std::ofstream os("foo.txt");
    myclass.printSomeData(os);
    

    您正在传递对现有 std::ofstream 对象的引用,而不是临时对象。

    您也可以让printSomeData 获取const 引用,但大概您想更改函数中的流。

    【讨论】:

      【解决方案2】:
      void printSomeData(const std::ostream& str) const;
      //                   |
      //              notice const
      

      临时对象不能绑定到非const 引用,std::ofstream("foo.txt") 创建一个临时对象。

      或者你可以为函数提供一个非临时变量。

      【讨论】:

        【解决方案3】:
        void printSomeData(std::ostream& str) const;
        
        myclass.printSomeData(std::ofstream("foo.txt"));
        

        您尝试传递给引用临时对象的函数(即尝试将rvalue 绑定到lvalue-reference)。这是不正确的。可以用const std::ostream&,但是不好用,如果你会用C++11也可以用std::ostream&&

        void printSomeData(std::ostream&& str) const;
        myclass.printSomeData(std::ofstream("foo.txt"));
        

        但是在这种情况下你不能传递 ostream 类型的对象。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-18
          • 1970-01-01
          • 1970-01-01
          • 2016-09-23
          • 2015-04-23
          • 1970-01-01
          相关资源
          最近更新 更多