我目前正在学习c++一周,这是我的问题:
run.cpp
#include <iostream>
#include "Abc.h"
int main(){
int a;
std::cout << "Enter a : ";
std::cin >> a;
// Object Initialization
Abc AbcObj();
}
header Abc.h :#ifndef ABC_H
#define ABC_H
class Abc
{
public:
Abc();
protected:
private:
};
#endif // ABC_H
最后是我的实现用cpp文件 Abc.cpp :#include "Abc.h"
#include <iostream>
Abc::Abc()
{
std::cout << std::endl << "Object created ";
}
为什么我的控制台上没有输出?我希望“对象创建”应该在控制台上。这些文件位于同一目录中。
最佳答案
由于使用了不同的文件,因此不会出现错误,因此在此示例中我使用了一个文件
struct Foo
{
int a;
Foo()
{
std::cout << "Constructor called!";
}
};
int main()
{
Foo obj();
}
您为什么看不到该消息? You can read this thread这里的问题是,
Foo obj()
被当作function declaration。要解决此问题,您需要删除()
int main()
{
Foo obj;
}
Constructor called!
关于c++ - 单独文件中的简单类和标题不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64765049/