得到了一个简短的问题。为什么第一个程序可以工作,但是当我把它分成头文件/源文件时呢?我怎样才能解决这个问题? (错误是“Stud s [line 6 main.cpp]”没有默认构造函数)
这是我的代码:
工作人员:
#include <iostream>
#include <string>
using namespace std;
class Stud {
private:
string pren, surn;
unsigned int number;
public:
Stud(string p = "", string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
friend ostream& operator<<(ostream& os, Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
};
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}
现在拆分了:
stud.hpp:
#ifndef STUD_HPP
#define STUD_HPP
#include <iostream>
#include <string>
class Stud {
private:
std::string pren, surn;
unsigned int number;
public:
Stud(std::string, std::string, unsigned int);
friend std::ostream& operator<<(std::ostream&, const Stud&);
};
#endif
stud.cpp:
#include "stud.hpp"
Stud::Stud(std::string p = "", std::string s = "", unsigned int n = 0) : pren(p), surn(s), number(n)
{
return;
}
std::ostream& operator<<(std::ostream& os, const Stud& st) {
os << st.number << ", " << st.pren << " " << st.surn;
return os;
}
的main.cpp
#include <iostream>
#include "stud.hpp"
using namespace std;
int main() {
Stud s;
Stud test("x", "y", 123);
cout << s << endl;
cout << test << endl;
}