gpt4 book ai didi

C++无法创建类的实例

转载 作者:行者123 更新时间:2023-11-28 04:31:16 24 4
gpt4 key购买 nike

我无法理解为什么在我的以下代码中错误地实现了对象创建:

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com