gpt4 book ai didi

C++ 指针查询

转载 作者:行者123 更新时间:2023-11-30 01:53:22 26 4
gpt4 key购买 nike

所以我一直在玩弄静态、指针和类型定义,但我遇到了一堵砖墙,想知道是否有人可以提供一些见解。

我有一个类Utilsstatic ofstream称为 theLog我还有另一个类 Work利用 Utils::theLog .这是相关代码:

实用工具.h

#ifndef UTILS_H
#define UTILS_H

// includes

class Utils {
public:
static ofstream theLog;

// other code
}
#endif

工作.cpp

 // includes

typedef ofstream* pOfStream;
static pOfStream l = &(Utils::theLog); // l is a lowercase L

// constructor and destructor

void Work::doSomeWork() {
(*l) << "Hello, world!\n";
}
// other code

这会编译并且不会出现运行时错误。但是定义 pOfStream 的原因是为了消除用星号、括号和 Utils::theLog 填充我的代码.当我尝试替换 (*l) 时只有 l如:l << "Hello, world!\n";我收到编译器错误。我假设原因是运算符(operator) <<优先于 * , 即使 l类型为 pOfStream ,它被定义为指向 ofstream 的指针对象,但代码并未隐式写入 *l << "Hello, world!\n"; .

我的问题是,有没有办法使用提取运算符 <<不必用括号和星号包围指针?同样,当您定义上述类型时 pOfStream然后分配一个变量 var到类型 pOfStream ,编译器是否只是通读代码并替换 pOfStream 的任何实例?与 ofstream*

我一直在搜索 SO 和 Google 寻找答案,但我不太确定如何表述这个问题。

最佳答案

为什么不直接拿流的引用,比如

ostream &l = Utils::theLog;
l << "Hello, World!\n";

这样就不用用指针了。

关于C++ 指针查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com