【问题标题】:Why does code in constructor not run when called from another file?为什么从另一个文件调用时构造函数中的代码不运行?
【发布时间】:2020-12-11 18:32:52
【问题描述】:

ma​​in.cpp


#include <iostream>
    
#include "shreeman.h"
    
using namespace std;
    
int main(){
    
    Shreeman object;
}


shreeman.h

#ifndef SHREEMAN_H
#define SHREEMAN_H
    
    
class Shreeman
{
    public:
        shreeman();
};
    
#endif // SHREEMAN_H

shreeman.cpp


#include <iostream>
#include "shreeman.h"

using namespace std;

Shreeman::shreeman()
{
    cout<<"Hello Hello"<<endl;

}

为什么这段代码不输出“Hello Hello”?我在 main.cpp 文件中创建了一个对象,但控制台中没有打印任何内容。

【问题讨论】:

  • 你发了两次shreeman.h,没有发shreeman.cpp
  • shreeman 不是 Shreeman 的构造函数。
  • 你拼错了构造函数的名字——它有一个小写的s而不是一个大写的S(我希望你的编译器至少给出一个警告)?
  • @Shreeman24 你的类定义中的shreeman(); 是如何编译的?
  • @Shreeman24 我们无法为您提供帮助,因为您发布的代码是您认为的代码,而不是实际代码,而且区别很重要。请制作一个[Minimal Reproducible Example](如何创建一个Minimal, Reproducible Example)

标签: c++ class constructor


【解决方案1】:

Shreeman类中,shreeman()(小写s)不是一个有效的构造函数,它只是一个成员方法。它需要重命名为Shreeman()(大写S)才能成为一个构造函数(编译器应该已经警告过你)。 C++ 区分大小写,构造函数名称需要与类名完全匹配、大小写和全部匹配。

main.cpp

#include "shreeman.h"
    
int main()
{    
    Shreeman object;
}

shreeman.h

#ifndef SHREEMAN_H
#define SHREEMAN_H
    
class Shreeman
{
    public:
        Shreeman();
};
    
#endif // SHREEMAN_H

shreeman.cpp

#include <iostream>
#include "shreeman.h"

using namespace std;

Shreeman::Shreeman()
{
    cout << "Hello Hello" << endl;
}

【讨论】:

  • 它不应该在没有返回类型的情况下编译,不是吗?
  • @Shreeman24 所以你完全没有告诉我们编译器错误??
  • @RemyLebeau 他的意思是在 OP 的代码中。您暗示shreeman(); 是一个不是构造函数的成员,但这意味着它需要一个返回类型,而它没有。
  • @CaptainGiraffe 我没说过这样的话。但是,如果在方法声明中省略了返回类型,编译将简单地将其默认为 int 并且应该发出警告
  • @CaptainGiraffe 的 gcc 许可模式/VS 的不兼容模式将允许这样做
猜你喜欢
  • 1970-01-01
  • 2011-03-24
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2010-11-06
  • 2014-03-12
  • 2016-07-03
相关资源
最近更新 更多