C++ C++;无法创建类的实例
我无法理解为什么我的以下代码中的对象创建被错误地实现:C++ C++;无法创建类的实例,c++,c++11,C++,C++11,我无法理解为什么我的以下代码中的对象创建被错误地实现: #include <iostream> #include <string> class A { public: A(std::string apptype) : m_apptype(apptype) { std::cout << m_apptype << std::endl; } A(std::string&& apptype)
#include <iostream>
#include <string>
class A
{
public:
A(std::string apptype) : m_apptype(apptype)
{
std::cout << m_apptype << std::endl;
}
A(std::string&& apptype) : m_apptype(apptype)
{
std::cout << m_apptype << std::endl;
}
private:
std::string m_apptype;
};
int main()
{
A(std::string("Test"));
return 0;
}
你需要实例化你的对象,替换下面的行
A(std::string("Test"));
到
我假设您在使用“&&”创建初始化时尝试移动传递给“a”的值,但无法移动作为参数传递的函数string()创建的临时字符串,那么它也不会编译。您需要创建一个变量,如下所示:
std::string S("Test");
A a(S);
但它总是会复制S,您需要的是一个对象,您可以复制或移动传递给它的字符串。解决方案是在将“S”传递到“a”时移动,如下所示:
class A {
public:
A(const std::string apptype) : m_apptype(apptype) {
std::cout << m_apptype;
}
private:
std::string m_apptype;
};
int main() {
std::string S("Test");
A a(S);
std::cout << (S.empty()?" moved":" copied") << " from S\n";
A b(move(S));
std::cout << (S.empty()?" moved":" copied") << " from S\n";
return 0;
}
A类{
公众:
A(const std::string apptype):m_apptype(apptype){
std::cout首先,您应该创建一个类A的对象
A(std::string(“Test”);
没有创建类A的对象,只是调用类A的参数化构造函数
您应该将其改为`A obj(std::string(“Test”)
其次,A(std::string&&apptype):m_apptype(apptype)
未正确实现。成员初始化正在尝试将字符串引用apptype
分配给字符串对象m_apptype
,这可能会导致意外结果
更正,考虑到您共享的示例,这些应该可以让它正常工作。其中没有std::map
。而且看起来您的编译器是为C++03配置的,并且被右值引用阻塞。更正了问题标题“是否在启用C++11支持的情况下编译?”感谢compile-std=C++11选项解决了问题issueIt需要是A(std::string&&apptype):m_apptype(std::move(apptype)){}
,您现在正在复制它,而不是移动。而且您实际上不需要它,您可以在通过值传递std::string
时移动参数。当第一个接受const std::string&
std::string S("Test");
A a(S);
class A {
public:
A(const std::string apptype) : m_apptype(apptype) {
std::cout << m_apptype;
}
private:
std::string m_apptype;
};
int main() {
std::string S("Test");
A a(S);
std::cout << (S.empty()?" moved":" copied") << " from S\n";
A b(move(S));
std::cout << (S.empty()?" moved":" copied") << " from S\n";
return 0;
}