【发布时间】:2015-10-12 16:49:49
【问题描述】:
我想了解一个类的 ostream 运算符在目标文件中的“位置”。在下面的代码示例中,我设计了一个与 ostream 运算符交朋友的 C++ 类 DeltaTimer。下面是“nm DeltaTimer.o”的输出。 在此输出中对“ostream”进行 Grepping 会针对符号类型“U”(即未定义)显示它们。但是代码编译(包括 main.cpp 以确保完整性)并成功链接,并按预期执行,这意味着没有任何未定义的内容。但我不明白 ostream 运算符在“nm”的输出中解析为什么,如果有人能提供建议,我将不胜感激。 谢谢。
DeltaTimer.h:
#ifndef DeltaTimer_h
#define DeltaTimer_h
#include <iostream>
class DeltaTimer
{
public:
DeltaTimer();
virtual ~DeltaTimer();
void Foo();
private:
int m_foo;
friend std::ostream& operator<<(std::ostream& os, const DeltaTimer& rDeltaTimer);
};
#endif // DeltaTimer_h
DeltaTimer.cpp:
#include "DeltaTimer.h"
#include <iostream>
DeltaTimer::DeltaTimer() : m_foo(5)
{
std::cout << "DeltaTimer ctor" << std::endl;
}
DeltaTimer::~DeltaTimer()
{
std::cout << "DeltaTimer dtor" << std::endl;
}
void DeltaTimer::Foo()
{
std::cout << "DeltaTimer.m_foo == " << m_foo << std::endl;
}
std::ostream& operator<<(std::ostream& os, const DeltaTimer& rDeltaTimer)
{
os << "DeltaTimer[m_foo(" << rDeltaTimer.m_foo << ")]" << std::endl;
}
// This function is just a sanity-check for the output of "nm"
void Bar()
{
std::cout << "void Bar()" << std::endl;
}
main.cpp:
#include "DeltaTimer.h"
#include <iostream>
int main()
{
DeltaTimer deltaTimer;
std::cout << deltaTimer << std::endl;
}
“nm”的输出:
>nm DeltaTimer.o
00000000000001a7 t _GLOBAL__I__ZN10DeltaTimerC2Ev
0000000000000145 T _Z3Barv
0000000000000167 t _Z41__static_initialization_and_destruction_0ii
00000000000000b0 T _ZN10DeltaTimer3FooEv
0000000000000000 T _ZN10DeltaTimerC1Ev
0000000000000000 T _ZN10DeltaTimerC2Ev
000000000000008a T _ZN10DeltaTimerD0Ev
0000000000000040 T _ZN10DeltaTimerD1Ev
0000000000000040 T _ZN10DeltaTimerD2Ev
U _ZNSolsEPFRSoS_E
U _ZNSolsEi
U _ZNSt8ios_base4InitC1Ev
U _ZNSt8ios_base4InitD1Ev
U _ZSt4cout
U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
0000000000000000 b _ZStL8__ioinit
U _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
0000000000000000 V _ZTI10DeltaTimer
0000000000000000 V _ZTS10DeltaTimer
0000000000000000 V _ZTV10DeltaTimer
U _ZTVN10__cxxabiv117__class_type_infoE
U _ZdlPv
00000000000000f1 T _ZlsRSoRK10DeltaTimer
U __cxa_atexit
U __dso_handle
U __gxx_personality_v0
>nm DeltaTimer.o | grep -i ostream
U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
U _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
【问题讨论】:
-
好吧,它在你的目标文件中是未定义的,因为它最终是从 c++ 标准库中链接进来的。为什么你认为它应该存在于你的目标文件中?
-
std::cout 从 c++ stl 链接进来,但我在我的代码中实现了 ostream 运算符,即 DeltaTimer.cpp,所以它必须存在于编译的目标代码中,确实如此,根据下面@Barry 的回答。谢谢大家。
-
我一直指的是
U符号。
标签: c++ operator-overloading ostream object-files