问题
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"
}
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);
};
回答1:
First, you should put quotation marks around the email address:
#define SERVICE_EMAIL "service@company.com"
Second, you should not use #define
at all. Use a const
variable instead:
const String SERVICE_EMAIL = "service@company.com";
#define
s are type unsafe, have no scope and are generally evil.
Last, you may want to consider using std::string
instead of your String
class.
Update:
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";
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;
Better solution:
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;
}
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.
回答2:
The problem is, I think since I don't know the String
type, is that SERVICE_EMAIL should be a string literal:
#define SERVICE_EMAIL "service@company.com"
but then, it should fail even in the latter solution. Maybe your code snippet doesn't show the real problem.
回答3:
#define SERVICE_EMAIL "service@company.com"
回答4:
What's the type of service@company.com? I think you wish to use a string to store an email address.
Try:
#define SERVICE_EMAIL "service@company.com"
来源:https://stackoverflow.com/questions/5896230/unqualified-id-before-string-constant