在 msvc 中,我有这样的函数并且它可以构建,但在 gcc 中它不喜欢它。
void classname::a(std::string &text)
{
stdStringFromClass = text;
}
void classname::b(char *text)
{
a(std::string(text));
}
这里的问题出在 &,我认为 gcc 很担心,因为我刚刚创建了那个 std::string,通过引用传递是有风险的,所以它没有构建,但 msvc 甚至没有警告我。
为什么 c++ 对 gcc 不正确我一直听说 msvc 比 gcc 更严格。
谢谢
错误
AguiWidgetBase.cpp: In member function ‘void AguiWidgetBase::setText(char*)’:
AguiWidgetBase.cpp:91:27: error: no matching function for call to ‘AguiWidgetBase::setText(std::string)’
AguiWidgetBase.cpp:80:6: note: candidates are: void AguiWidgetBase::setText(std::string&)
AguiWidgetBase.cpp:88:6: note: void AguiWidgetBase::setText(char*)
这样可以吗?
void classname::a(std::string &text)
{
stdStringFromClass = text;
}
void classname::b(char *text)
{
std::string k = text;
a(k);
}
最佳答案
我认为这是 Visual Studio 从很久以前就支持的旧编译器扩展,但为了兼容性,它在现代 Visual C++ 中保留。尝试禁用编译器扩展(/Za
标志),看看会发生什么。
或者,使用 /W4
标志来获得最大警告,它应该会提示:
warning C4239: nonstandard extension used
在 GCC 上我得到常量引用错误:
error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’
关于c++ - 为什么 msvc 让我这样做而不是 gcc/g++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897702/