C++类构造函数混淆

Posted

技术标签:

【中文标题】C++类构造函数混淆【英文标题】:C++ Class constructor confusion 【发布时间】:2013-04-27 23:01:29 【问题描述】:

我有 2 个文件,Chrono.cpp 和 Chrono.h。

Chrono.h

class Appointment 
public:

    Appointment( Date d , string n ) ;
    Appointment() ;

    int get_day() const  return date.d; 
    int get_month() const  return date.m; 
    int get_year() const  return date.y; 
    string get_name() const  return name ; 

    Date date ;
    string name ;

 ;

Chrono.cpp

Appointment::Appointment( Date dd , string nn )
    : date( dd ) , name( nn ) 
 
    //if(!is_date(yy,mm,dd))throw Invalid(); 

我继续收到此错误,或者说它与 .h 文件不匹配的变体。

Chrono.cpp:17:1: error: prototype for āChrono::Appointment::Appointment(Chrono::Date, String)ā does not match any in class āChrono::Appointmentā
Chrono.h:34:7: error: candidates are: Chrono::Appointment::Appointment(Chrono::Appointment&&)
Chrono.h:34:7: error:                 Chrono::Appointment::Appointment(const Chrono::Appointment&)
Chrono.h:42:2: error:                 Chrono::Appointment::Appointment(Chrono::Date, std::string)
Chrono.h:41:2: error:                 Chrono::Appointment::Appointment()

两个文件都有#include 字符串,并且.cpp 文件位于std 命名空间中。我也尝试在头文件中使用 std::string 。到目前为止,我所做的一切都没有奏效。任何帮助表示赞赏。另请注意,日期在其他地方定义并且工作正常。

【问题讨论】:

【参考方案1】:

您拼错了“字符串”。在您的代码中显示为string,但在错误中显示为String

【讨论】:

编译器没有将它识别为std::string,所以它输出String。代码中拼写正确 @Joshua:请向我们展示您在文件 Chrono.cpp 中的 literal 第 17 行。

以上是关于C++类构造函数混淆的主要内容,如果未能解决你的问题,请参考以下文章

C++中派生类的构造函数怎么显式调用基类构造函数?

c++关于派生类的拷贝构造函数

C++创建派生类对象时,调用构造函数顺序

如何从另一个构造函数调用 C++ 类构造函数 [重复]

C++中,继承时,创建子类对象,能否在子类构造函数初始化列表里调用基类构造函数?

C++类-构造函数的重载