我正在学习C ++并且教程要求我将另一个项目添加到我现在拥有的项目中。 此外,我被要求使用前向声明,以便我可以使用该添加的文件。
这是我的主要项目:
public class Note implements Serializable {
private long mDateTime; //creation time of the note
private String mTitle; //title of the note
private String mContent; //content of the note
public Note(long dateInMillis, String title, String content) {
mDateTime = dateInMillis;
mTitle = title;
mContent = content;
}
public void setDateTime(long dateTime) {
mDateTime = dateTime;
}
public void setTitle(String title) {
mTitle = title;
}
public void setcontent(String content) {
mContent = content;
}
public long getDateTime() {
return mDateTime;
}
public String getDateTimeFormatted(Context context) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
, context.getResources().getConfiguration().locale);
formatter.setTimeZone(TimeZone.getDefault());
return formatter.format(new Date(mDateTime));
}
public String getTitle() {
return mTitle;
}
public String getContent() {
return mContent;
}
}
这是添加的名为io.cpp的文件:
#include <iostream>
#include "io.cpp"
using namespace std;
int readNumber();
void writeResult(int x);
int main() {
int x = readNumber();
int y = readNumber();
writeResult(x + y);
return 0;
}
![And here's a screenshot so you can see what error I'm getting which talks about multiple definition and you can see where those two files are added. According to the tutorial my code is okay but compiler complains. Why ?] 1
答案 0 :(得分:0)
在codeblocks中,创建新类时,它应该自动头文件。使用头文件进行编程是最好的做法。这是我尝试的代码,它使用了io.h。
<强>的main.cpp 强>
#include <iostream>
#include "io.h"
using namespace std;
io inOut;
int main()
{
int x = inOut.readNumber();
int y = inOut.readNumber();
inOut.writeResult(x + y);
return 0;
}
<强> io.h 强>
#ifndef IO_H
#define IO_H
class io
{
public:
int readNumber();
void writeResult(int);
};
#endif
<强> io.cpp 强>
#include <iostream>
#include "io.h"
using namespace std;
int io::readNumber()
{
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void io::writeResult(int x)
{
cout << "Sum of your numbers is " << x << endl;
}
我使用代码块来编译上面编写的代码,并且它运行得很好。