c++ - 如何在 main() C++ 中调用构造函数?

标签 c++ class constructor makefile program-entry-point

我有两个类(class)。

文件信息.cpp:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class fileInfo{

private:

string fileName;
string fileType;

public:
/** 
**/
fileInfo(string s){
    fileName = s;
    fileType = "hellooo";

}
string getName() {
    return fileName;
}
};

主要.cpp

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]){

fileInfo f("test");
std::cout << f.getName();

}

fileInfo 对象“f”未被初始化,我收到一条错误消息,指出 fileInfo 不在范围内。我正在使用 makefile 来编译我的代码,看起来像这样。

all: main.cpp fileInfo.cpp
    g++ main.cpp fileInfo.cpp -o out

最佳答案

正确的做法是:

文件信息.h:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class fileInfo{

private:

  string fileName;
  string fileType;

public:

  fileInfo(string s);

  string getName();
};

文件信息.cpp:

#include "fileInfo.h"

fileInfo::fileInfo(string s){
    fileName = s;
    fileType = "hellooo";
}

string fileInfo::getName() {
    return fileName;
}

主要.cpp

#include <iostream>
#include <string>
#include "fileInfo.h"

using namespace std;
int main(int argc, char* argv[]){

  fileInfo f("test");
  std::cout << f.getName();

}

关于c++ - 如何在 main() C++ 中调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930418/

相关文章:

typescript 类不实现接口(interface)类型

c++ - 为什么在 header 中的类声明中声明变量时会出现错误?

java - 当我正确查看未定义的方法(构造函数)时,出现有关未定义方法(构造函数)的错误? ( java )

python - 使用 Python 将代码直接导入脚本?

同一类的Java组合和聚合?

constructor - F#:如何使用 "with"构造函数获取更多值

c++ - OpenCV 在使用 imgproc 函数时出错

c++通过模板实例化类

c++ - ns2 中的段错误

c++ - 如何使用正态分布生成最小值和最大值之间的整数?