1

我对 C++ 还很陌生,并且仍在尝试理解指针以及何时需要它们。但是对于这个问题,我正在四处寻找创建头文件和类。我的第一个“测试”是创建一个可以处理“日志”的类所以我这样做了。

记录器.h

#pragma once
#include <iostream>
using namespace std;

class Logger
{
    public:
        Logger();
        void logC(const char* message);
        void logCA(const char message[]);
        void logS(string message);
};

记录器.cpp

#include "Logger.h"

Logger::Logger() {

}

void Logger::logC(const char* message)
{
    cout << message << endl;
}

void Logger::logCA(const char message[])
{
    cout << message << endl;
}

void Logger::logS(string message)
{
    cout << message << endl;
}

然后在我的主要功能上,我只是像这样使用它们。

#include "Logger.h"

int main(){

    Logger myLogger;

    myLogger.logC("Hello");
    myLogger.logCA("Alo");
    myLogger.logS("Hola");

    cout << endl;
    system("pause");
    return 0;
}

这里有几个问题。为什么我会使用一种方法而不是其他方法。而且,在 const char* 方法上,为什么这是一个指向 char 的指针,它需要一个 char 数组作为有效,而且,如果它接收到一个 char 位置的地址,为什么输出是整个数组而不是它所在的内存地址。(而且它也“知道”在哪里停止,它不会从那个地址打印并且永远不会打印)

4

1 回答 1

1
void logC(const char* message);

Accepts a pointer to a char buffer. This is also known as a C-string (as long as it's null terminated, which yours is, because it's a string literal).

void logCA(const char message[]);

Exactly the same. Don't let the [] fool you: this is literally the same as const char* message. That's not because arrays are pointers: they're not. It's a weird oddity from C history. A function parameter with what looks like "array type" with no dimensions, is treated as a pointer parameter instead. Yuck!

void logS(string message);

Accepts a std::string. These can be constructed from C-strings, and this is happening for you behind the scenes when you pass in your string literal.

Which is best? That's highly subjective. Arguably you want a const std::string_view, which can accept any of these at no cost. But a deep discussion on the differences is out of scope here; it can be found in your book, however.

it's receiving an address to the location of a char, why the output is the whole array and not the memory address it's on

Because cout has a special rule for char*, knowing that you usually want these to be treated like strings, because you do. Instead of printing the pointer's value (a memory address), it dereferences that and prints all the characters in the buffer it points to, ending at the null terminator. It's a feature.

If you use a cast to another pointer type, you can "turn that off", e.g. cout << (void*)message now you'll see an address.

于 2020-03-15T14:42:30.410 回答