C++ 抑制警告:未使用的变量

C++ 抑制警告:未使用的变量,c++,c++11,suppress-warnings,C++,C++11,Suppress Warnings,尝试使用以下命令编译我的代码: g++Error.cpp-Wall-std=c++0x-o文件名 我得到一个警告:错误。cpp:40:30:警告:未使用的变量“ostr”[-Wunused variable] 我已经看到可以删除-Wall以抑制警告,但我不想这样做。我想在我的代码中加入一些东西来解决它。仅编码了约6个月,顺便说一句 // Error.cpp #define _CRT_SECURE_NO_WARNINGS // Tried using #define _CRT_UNUSED t

尝试使用以下命令编译我的代码: g++Error.cpp-Wall-std=c++0x-o文件名 我得到一个警告:错误。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;
}
//Error.cpp
#定义\u CRT\u安全\u无\u警告
//尝试使用#define(定义)CRT(未使用)然后在下面执行(ostr)CRT(未使用)
#包括
#包括
#包括
#包括“Error.h”
无效错误::消息(常量字符*错误消息){
清除();
m_message=新字符[strlen(errorMessage)+1];
strcpy(m_消息,errorMessage);
}
无效错误::运算符=(常量字符*错误消息){
消息(错误消息);
}
错误::运算符const char*()const{
返回m_消息;
}
错误::运算符bool()常量{
返回m_message==nullptr;
}
std::ostream&ict::operator如图所示,问题不在于函数参数
ost
:返回语句使用的参数

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

if (!bool(E)) { const char*(ostr); }
括号是合法的,但多余的:这一行相当于:

if (!bool(E)) { const char *ostr; }
您正在声明一个局部变量(恰好隐藏了函数参数),而没有将其用于任何用途

如果要将消息从
E
流式传输到
ost
,必须执行以下操作:

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

if(!bool(E)){ostr您是否打算执行以下操作

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

std::ostream&ict::operator如果您只想抑制文件中的警告,您可以查看文档的这一部分:第40行是哪一行?我打赌这是带有
if
的一行,您在其中声明了
const char*
类型的局部变量
ostr
(名称周围有不必要的括号)。您想在那里实现什么?警告在
if(!bool(E)){const char*(ostr);}行上
,它声明了一个名为
ostr
的变量,该变量隐藏了函数参数
ostr
。您能解释一下该语句实际实现了什么吗???…因为,很可能它没有实现。仅供参考,我们在此处保留了一个列表,您可能需要查看一个。编译器错误和警告:l你知道他们起源于哪一行。实际上,在你的实际问题中包含这些信息,并且注意它,在诊断C++错误和警告时很重要。但是,这正是我所要做的,但是,函数是全局的,MyMead不能被它访问。@ JCyDARKO,因为你没有包含D,所以我们不知道。在你的问题中,
Error
类的定义…@Angew我确实表明操作符重载是ict名称空间的一部分,而不是Error类的一部分。我当时认为这已经足够了,但我猜你不能假设该成员是私有的或公共的……让操作符成为错误的“朋友”。