我无法理解为什么以下代码中的对象创建错误地实现:
#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;
}
编译代码时出现以下错误:
$ c++ Calender.cpp
Calender.cpp:10:14: error: expected ',' or '...' before '&&' token
A(std::string&& apptype) : m_apptype(apptype)
^
Calender.cpp:10:1: error: 'A::A(std::string)' cannot be overloaded
A(std::string&& apptype) : m_apptype(apptype)
^
Calender.cpp:6:1: error: with 'A::A(std::string)'
A(std::string apptype) : m_apptype(apptype)
^
Calender.cpp: In constructor 'A::A(std::string)':
Calender.cpp:10:38: error: 'apptype' was not declared in this scope
A(std::string&& apptype) : m_apptype(apptype)
^
答案 0 :(得分:1)
首先,您应该创建一个A类的对象
A(std::string("Test"));
不是在创建类A的对象,而只是在调用类A的参数化构造函数。
您应该改为将其更改为`A obj(std :: string(“ Test”));;。
第二,A(std::string&& apptype) : m_apptype(apptype)
的实现不正确。成员初始化正在尝试将字符串引用apptype
分配给字符串对象m_apptype
,这可能会导致意外结果。
更正后,考虑到您共享的示例,这些应该可以使它正常工作。
答案 1 :(得分:0)
您需要实例化对象A并替换以下行
A(std::string("Test"));
到
A 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;
}