抑制警告:未使用的变量



尝试使用以下命令编译我的代码: g error.cpp -wall -std = C 0x -o fileName
我会收到警告: error.cpp:40:30:警告:未使用的变量" OSTR" [-wunused-variable]

我已经看到 -wall 可以删除以抑制警告,但我不想这样做。我想在我的代码中放一些东西以围绕它来工作。仅编码约6个月。

// Error.cpp
#define _CRT_SECURE_NO_WARNINGS 
// Tried using #define _CRT_UNUSED then doing _CRT_UNUSED(ostr) down below
#include <iomanip>
#include <iostream>
#include <cstring>
#include "Error.h"
void Error::message(const char* errorMessage) {
    clear();
    m_message = new char[strlen(errorMessage) + 1];
    strcpy(m_message, errorMessage);
}
void Error::operator=(const char* errorMessage) {
    message(errorMessage);
}
Error::operator const char*() const {
    return m_message;
}
Error::operator bool() const {
    return m_message == nullptr;
}
std::ostream& ict::operator<<(ostream& ostr, const Error& E) {
    (void)ostr; // This didn't work, i still get the warning with or without it
    if (!bool(E)) { const char*(ostr); }
    return ostr;
}

编辑:是的第40行是IF的行。由于某种原因,我以为const char*(ostr)m_message放置在ostr中,然后可以将其返回并在其他地方输出。我不知道我只是在IF语句中创建一个无用的变量,以为我的操作员过载会发挥作用,尽管我不是100%确定我是否正确使用它...

正如此实时示例所示,问题不是函数参数 ostr:返回语句使用。

问题是您在if中声明的类型const char *的局部变量ostr

if (!bool(E)) { const char*(ostr); }

括号是合法的,但多余:该线等同于此:

if (!bool(E)) { const char *ostr; }

您正在声明局部变量(恰好隐藏了函数参数),而不是将其用于任何内容。

如果要将消息从E流传输到ostr,则必须这样做:

if (!bool(E)) { ostr << static_cast<const char*>(E); }

您的意思是要做以下操作吗?

std::ostream& ict::operator<<(ostream& ostr, const Error& E) {
    if (!bool(E)) { ostr << E.m_message; }
    return ostr;
}

最新更新