[英]C++ calling constructor from another file
I have those 3 files of code, and I want to to print "Mountains were just created" from the constructor. 我有这3个代码文件,我想从构造函数中打印“刚创建的山”。 Could you tell me please where I am wrong and what I must to do?
你能告诉我哪里错了,我该怎么办?
Mountains.h 山.h
#ifndef MOUNTAINS_H
#define MOUNTAINS_H
class Mountains{
public:
Mountains();
~Mountains();
};
#endif
Mountains.cpp 山.cpp
#include <cstdlib>
#include <iostream>
#include "Mountains.h"
Mountains::Mountains()
{
cout<<"Mountains were just created"<<endl;
}
Mountains::~Mountains()
{
cout<<"Mountains are about to be destroyed"<<endl;
}
main.cpp main.cpp
#include <cstdlib>
#include <iostream>
#include "Mountains.h"
int main(int argc, char *argv[])
{
Mountains m();
system("PAUSE");
return EXIT_SUCCESS;
}
I would expect, "Mountains were just created", to be written to the console when I call Mountains m();
我希望当我调用
Mountains m();
时将“刚刚创建的山”写入控制台Mountains m();
This is not happening. 这没有发生。
The problem is right here: 问题就在这里:
Mountains m();
That is not a default-initialized Mountains
object called m
. 那不是称为
m
的默认初始化的 Mountains
对象。 It is a function called m
that takes no parameters and returns a Mountains
. 这是一个名为
m
的函数,该函数不带任何参数并返回Mountains
。
To create a default-initialized Mountains
you need to do: 要创建默认初始化的
Mountains
您需要执行以下操作:
Mountains m;
or in C++11 : 或在C ++ 11中 :
Mountains m{};
You are also missing the std::
qualification when using things from the Standard Library , like cout
or endl
. 当使用标准库中的东西(例如
cout
或endl
时,您还缺少std::
资格。 That's assuming you don't do using namespace std;
假设您不
using namespace std;
, although discoraged, in a relevant place. ,尽管不合理,但在相关的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.