如何在 main() C++ 中调用构造函数?
How can I call a constructor in main() c++?
我有两个类。
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
#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
正确的做法是:
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:
#include "fileInfo.h"
fileInfo::fileInfo(string s){
fileName = s;
fileType = "hellooo";
}
string fileInfo::getName() {
return fileName;
}
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();
}
我有两个类。
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
#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
正确的做法是:
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:
#include "fileInfo.h"
fileInfo::fileInfo(string s){
fileName = s;
fileType = "hellooo";
}
string fileInfo::getName() {
return fileName;
}
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();
}