我有一个函数,它将ostream引用作为参数,将一些数据写入流,然后返回对同一个流的引用,如下所示:
#include <iostream>
std::ostream& print( std::ostream& os ) {
os << " How are you?" << std::endl;
return os;
}
int main() {
std::cout << "Hello, world!" << print( std::cout ) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
How are you?
Hello, world!0x601288
Run Code Online (Sandbox Code Playgroud)
但是,如果我将链接表达式分成两个语句,就像这样
int main() {
std::cout << "Hello, world!";
std::cout << print( std::cout ) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
然后我至少在输出中得到正确的顺序,但仍然得到一个十六进制值:
Hello, world! How are you?
0x600ec8
Run Code Online (Sandbox Code Playgroud)
我想了解这里发生了什么.正常函数是否优先operator<<,这就是输出顺序反转的原因?编写将数据插入到一个ostream但也可以链接的函数的正确方法是什么operator<<?
在工作中,我最近为从已发布的规范实现的类编写了一个小于运算符,该类具有许多属性,其中六个用于唯一标识类的实例.(为了这个问题,我们将这些属性称为af.)此外,这六个属性有六种不同的类型.我将运算符定义为:
bool operator<(const Class& lhs, const Class& rhs)
{
bool retval = (&lhs != &rhs);
if (retval == true)
{
if (lhs.a == rhs.a)
{
if (lhs.b == rhs.b)
{
if (lhs.c == rhs.c)
{
if (lhs.d == rhs.d)
{
if (lhs.e == rhs.e)
{
retval = (lhs.f < rhs.f);
} else {
retval = (lhs.e < rhs.e);
}
} else {
retval = (lhs.d < rhs.d);
}
} else {
retval = (lhs.c < rhs.c);
}
} else { …Run Code Online (Sandbox Code Playgroud) 背景:我正在为一个不是我编写的C库编写C++包装器接口.我的包装类模仿了库结构,在这个库中,有些成员struct b指向了成员struct a.该库的文档说:"不要销毁struct a之前的变量struct b." 实际上应该允许这样的情况,所以我想在代码中更好地处理这种情况.因此,在我的包装器中,如果class A有一个或多个class B指向它的实例的实例在B的所有实例之前被销毁,我想将数据从A复制到B的每个实例.目前,我用公共处理这个成员函数,如下:
// some code shortened or not shown
struct a {
int d; // in reality, data is much more complicated
};
struct b {
int* d;
};
class B;
class A {
struct a a_;
vector<B*> registered_bs_; // should probably use unordered_set
public:
~A(void) { for (iterator it: registered_bs_) (*it)->copyA(); } // C++0x for
void registerB(B* b) { registered_bs_.push_back(b); } …Run Code Online (Sandbox Code Playgroud)