代码之家  ›  专栏  ›  技术社区  ›  Programmer

C++无法创建类的实例

  •  0
  • Programmer  · 技术社区  · 8 年前

    我不明白为什么我下面代码中的对象创建被错误地实现了:

    #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)
                                          ^
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   TheArchitect    8 年前

    A(std::string("Test"));
    

    到

    A a(std::string("Test"));
    

    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;
    }
    
        2
  •  1
  •   Shrikanth N    8 年前

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

    您应该将其改为“A obj(std::string(“Test”);”;。

    A(std::string&& apptype) : m_apptype(apptype) 未正确实施。成员初始化正在尝试分配字符串引用 apptype 字符串对象 m_apptype 可能会导致意想不到的结果。