C++无法创建类的实例

标签 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) : 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)
                                      ^

最佳答案

首先,你应该创建一个类A的对象 A(std::string("Test")); 不是创建 A 类的对象,只是调用 A 类的参数化构造函数。

您应该改为将其更改为 `A obj(std::string("Test"));。

其次,A(std::string&& apptype) : m_apptype(apptype) 未正确实现。成员初始化试图将字符串引用 apptype 分配给字符串对象 m_apptype,这可能会导致意外结果。

更正,考虑到您分享的示例,这些应该可以正常工作。

关于C++无法创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52820050/

相关文章:

c++ - 目标及其 SO 依赖项的 CMake `INSTALL`

c++ - Qt 语言学家和谷歌翻译

c++ - 函数参数评估顺序与 Lambda 捕获评估顺序

c++ - 如何将 `std::chrono::milliseconds` 转换为 `boost::posix_time::milliseconds`

c++ - 访问类外的变量

c++ - 如何在 C++ 上的 "double"上使用按位运算符?

c++ - IFileDialog 在哪个库中

c++ - 为使用数组、 vector 、结构等传递给可变参数函数或可变参数模板函数的所有参数指定一种类型?

c++ - Pow() 真的需要 cmath header 还是 iostream 包含 cmath?

c++ - 使用 std::function 的隐式转换