字符串常量前的unqualified-id [英] Unqualified-id before string constant
问题描述
在编译以下代码时,出现错误字符串常量之前的预期非限定ID
On compiling following code I get error "expected unqualified-id before string constant"
In file "Notification_Constants.h"
namespace NOTIFICATION_CONSTANTS
{
#define SERVICE_EMAIL "service@company.com"
}
文件SendEmail.cpp
In file SendEmail.cpp
#include "Notification_Constants.h"
void UserPreferences::get_senders_email(String &_email)
{
_email = NOTIFICATION_CONSTANTS::SERVICE_EMAIL;
}
如果我按照以下说明进行分配,那么编译的原因是什么错误。
If i assign like following it works properly, what is the reason for the compilation error.
_email = SERVICE_EMAIL;
有一个类似的,但未提及原因。
There is a similar question but the reason is not mentioned.
带有相关方法的字符串类声明
String class declaration with relevant methods
class String
{
public:
String();
String(const String& src);
String(const char *new_str);
String& operator=(const String& src);
String& operator=(const char *new_str);
};
推荐答案
首先,您应该在电子邮件地址周围加上引号:
First, you should put quotation marks around the email address:
#define SERVICE_EMAIL "service@company.com"
第二,您完全不应使用 #define
。请使用 const
变量代替:
Second, you should not use #define
at all. Use a const
variable instead:
const String SERVICE_EMAIL = "service@company.com";
#define
类型不安全,具有没有范围,通常都是邪恶的。
#define
s are type unsafe, have no scope and are generally evil.
最后,您可能要考虑使用 std :: string
而不是您的 String
类。
Last, you may want to consider using std::string
instead of your String
class.
更新:
问题在于预处理器 #define
s只不过是文本替换。完成预处理程序后,编译器将看到
The problem is that the preprocessor #define
s are nothing more than text substitutions. When the preprocessor is done, your compiler will see
_email = NOTIFICATION_CONSTANTS::"service@company.com";
该命名空间中没有字符串常量。 SERVICE_EMAIL
不是任何类型的标识符-只是预处理器的一个指示,用任何出现的 SERVICE_EMAIL
替换为 service@company.com
。
There is no string constant in that namespace. SERVICE_EMAIL
is not an identifier of any kind - it is just an indication to the preprocessor to substitute any occurrence of SERVICE_EMAIL
with "service@company.com"
.
解决方案是删除名称空间限定符:
The solution is to remove the namespace qualifier:
_email = SERVICE_EMAIL;
更好的解决方案:
如果您无权访问 #define
,则应将其包装在头文件中,如果可能的话:
If you do not have access to the #define
, you should wrap it in a header file, if possible:
#include "Notification_Constants.h"
namespace NOTIFICATION_CONSTANTS {
const String REAL_SERVICE_EMAIL = SERVICE_EMAIL;
}
,然后使用 NOTIFICATION_CONSTANTS :: REAL_SERVICE_EMAIL
具有范围,是类型,是名称空间的适当成员,等等。
and then use NOTIFICATION_CONSTANTS::REAL_SERVICE_EMAIL
instead, which has scope, is a type, is a proper member of the namespace, and so on.
这篇关于字符串常量前的unqualified-id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!