Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在成员调用中实例化类_C++_Oop - Fatal编程技术网

C++ 在成员调用中实例化类

C++ 在成员调用中实例化类,c++,oop,C++,Oop,我的成员函数定义为: void printSomeData(std::ostream& str) const; 当我尝试以这种方式从另一个类调用该成员时: myclass.printSomeData(std::ofstream(“foo.txt”) 我得到以下错误: 错误:没有用于调用的匹配函数 'myclass::printSomeData(std::ofstream)' 注意:从'std::of Stream{aka'到参数1没有已知的转换 std::basic_of stream

我的成员函数定义为:

void printSomeData(std::ostream& str) const;
当我尝试以这种方式从另一个类调用该成员时:

myclass.printSomeData(std::ofstream(“foo.txt”)

我得到以下错误:

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

注意:从'std::of Stream{aka'到参数1没有已知的转换 std::basic_of stream}'to'std::ostream&{aka std::basic_ostream&}'

但是,如果我调用函数首先实例化ofstream,如下面所示,我不会得到任何错误,我并不真正理解:

std::ofstream foo("foo.txt");
myclass.printSomeData(foo);
有人能给我一个线索吗

多谢各位

void printSomeData(const std::ostream& str) const;
//                   |
//              notice const
临时变量不能绑定到非
const
引用,并且
std::ofstream(“foo.txt”)
创建临时变量

或者,您可以为函数提供非临时值

临时变量不能绑定到非
const
引用,并且
std::ofstream(“foo.txt”)
创建临时变量


或者,您可以为函数提供非临时引用。

您不能将临时引用绑定到非常量引用,您正在执行以下操作:

myclass.printSomeData(std::ofstream("foo.txt"));
                            ^ temporary std::ostream object
何时可以改为执行此操作:

std::ofstream os("foo.txt");
myclass.printSomeData(os);
您正在传递对现有
std::ofstream
对象的引用,而不是临时对象


您还可以使
printSomeData
接受
const
引用,但您可能希望更改函数中的流。

您无法将临时引用绑定到非const引用,您正在执行以下操作:

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

myclass.printSomeData(std::ofstream("foo.txt"));
何时可以改为执行此操作:

std::ofstream os("foo.txt");
myclass.printSomeData(os);
您正在传递对现有
std::ofstream
对象的引用,而不是临时对象

您还可以使
printSomeData
获取
const
引用,但您可能希望更改函数中的流

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

myclass.printSomeData(std::ofstream("foo.txt"));
您尝试传递给引用临时对象的函数(即尝试将
rvalue
绑定到
lvalue引用
)。这是不正确的。您可以使用
const std::ostream&
,但这并不好,如果您可以使用C++11,也可以使用
std::ostream&&

void printSomeData(std::ostream&& str) const;
myclass.printSomeData(std::ofstream("foo.txt"));
但在这种情况下,不能传递类型为ostream的对象

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

void printSomeData(std::ostream&& str) const;
myclass.printSomeData(std::ofstream("foo.txt"));
但在这种情况下,不能传递类型为ostream的对象