简体   繁体   English

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

[英]How can I call a constructor in main() c++?

I have two classes. 我有两节课。

fileInfo.cpp: fileInfo.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;
}
};

main.cpp main.cpp中

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

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

}

The fileInfo object "f" is not being initialized and I get an error saying that fileInfo is not in scope. fileInfo对象“ f”未初始化,并且我收到一条错误消息,指出fileInfo不在范围内。 I am using a makefile to compile my code which looks like. 我正在使用一个makefile来编译我的代码,如下所示。

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

Here's the correct way to do it: 这是正确的方法:

fileInfo.h: fileInfo.h:

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

class fileInfo{

private:

  string fileName;
  string fileType;

public:

  fileInfo(string s);

  string getName();
};

fileInfo.cpp: fileInfo.cpp:

#include "fileInfo.h"

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

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

main.cpp main.cpp中

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

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C ++中调用可变参数模板构造函数? - How can I call variadic template constructor in c++? C ++如何从具有一个参数的派生类构造函数调用具有两个参数的超类构造函数? - C++ How can I call superclass constructor with two parameters from derived class constructor with one parameter? 构造函数可以在c ++中调用另一个构造函数吗? - Can constructor call another constructor in c++? 为什么我可以在C ++中调用已删除的私有构造函数? - Why can I call deleted, private constructor in C++? 为什么我不能用c ++中的new调用参数化构造函数? - Why can't I call a parameterized constructor with new in c++? 我可以在 dart ffi 中调用 C++ 构造函数 function 吗? - Can I call a C++ constructor function in dart ffi? 我可以在 C++ 中从另一个构造函数调用构造函数(做构造函数链接)吗? - Can I call a constructor from another constructor (do constructor chaining) in C++? C++ 如何根据作为输入传递的参数调用一个或另一个构造函数? - C++ How can I call one constructor or the other depending on the parameters passed as input? C ++:如何在不创建对象的情况下在main函数中调用方法 - c++ : how can I call a method in main function without creating an object 如何使用模板调用内部类的构造函数? - c++ How do i call a constructor of an interior class with templates?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM