问题:
为什么会发生以下错误?
隐式声明的'Clothing :: Clothing()的定义
上下文:
作为一项任务,我必须在Clothing类中进行构造函数,析构函数和方法。我尝试在 clothing.cpp 中定义构造函数时遇到问题。我已经读过问题所在,是因为我没有在 clothing.h 中声明构造函数,但是我想我是如何做到的,就声明了。我不知道问题出在哪里。
我的代码:
clothing.h:
#ifndef CLOTHING_H_
#define CLOTHING_H_
#include <string>
#include <iostream>
using namespace std;
class Clothing {
private:
int gender;
int size;
string name;
public:
Clothing();
Clothing(const Clothing &t);
Clothing(int gender, int size, string name);
~Clothing();
int getGender();
int getSize();
string getName();
void setGender(int gender1);
void setSize(int size1);
void setName(string name1);
void print();
void toString();
};
#endif /* CLOTHING_H_ */
clothing.cpp:
#include <iostream>
#include "clothing.h"
#include <string>
#include <sstream>
using namespace std;
Clothing::Clothing() :
gender(1),
size(1),
name("outofstock") {
}
Clothing::Clothing(const Clothing& t) :
gender(t.gender),
size(t.size),
name(t.name) {
}
Clothing::Clothing(int gender, int size, string name) {
}
int Clothing::getGender() {
return gender;
}
int Clothing::getSize() {
return size;
}
string Clothing::getName() {
return name;
}
void Clothing::setGender(int gender1) {
gender = gender1;
}
void Clothing::setSize(int size1) {
size = size1;
}
void Clothing::setName(string name1) {
name = name1;
}
void Clothing::print() {
cout << name << " " << gender << " " << size << endl;
}
void Clothing::toString() {
stringstream ss;
ss << name << " " << gender << " " << size;
cout << ss.str();
}
错误: \ src \ clothing.cpp:7:21:错误:隐式声明的'Clothing :: Clothing()'的定义
\ src \ clothing.cpp:14:37:错误:隐式声明的“服装::服装(const服装&)”的定义
答案 0 :(得分:2)
错误是:您声明了析构函数,但未定义它。添加析构函数的定义或将其定义为默认值:
#ifndef CLOTHING_H_
#define CLOTHING_H_
#include <string>
#include <iostream>
using namespace std;
class Clothing {
private:
int gender;
int size;
string name;
public:
Clothing();
Clothing(const Clothing &t);
Clothing(int gender, int size, string name);
~Clothing() = default; // <-- add a default destructor
int getGender();
int getSize();
string getName();
void setGender(int gender1);
void setSize(int size1);
void setName(string name1);
void print();
void toString();
};
#endif /* CLOTHING_H_ */
解决此问题后,您的代码段将起作用:tio.run
如果您的代码有更多问题,则问题不在您提供的代码段之内。