关于默认构造函数,对象初始化/使用C++ OOP

Regarding default constructor an object initialization/usage in C++ OOP

本文关键字:初始化 对象 使用 OOP C++ 构造函数 于默认 默认      更新时间:2023-10-16

我最近开始学习C++的OOP,并开始解决有关它的示例任务。我想在为类CStudent创建默认构造函数后实例化该类的对象。但是,编译器无法编译代码。我想问这是为什么?

当你在类中写作时:

CStudent();
CStudent(string name, string fn);

。你只声明两个构造函数,一个默认(采用无参数(,另一个采用两个字符串。

声明它们后,您需要定义它们,就像定义方法getNamegetAverage一样:

// Outside of the declaration of the class
CStudent::CStudent() { }
// Use member initializer list if you can
CStudent::CStudent(std::string name, string fn) : 
name(std::move(name)), fn(std::move(fn)) { }

在 C++ 中,您还可以在类中声明它们时定义它们:

class CStudent {
// ...
public:
CStudent() { }
CStudent(std::string name, string fn) : 
name(std::move(name)), fn(std::move(fn)) { }
// ...
};

从 C++11 开始,您可以让编译器为您生成默认构造函数:

// Inside the class declaration
CStudent() = default;

这应该有效,正如 Holt 所评论的那样,您需要定义构造函数,您刚刚声明了它。

#include <iostream>
#include <string>
#include <list>
using namespace std;
class CStudent {
string name = "Steve";
list<int> scores;
string fn;
public:
CStudent() {};
CStudent(string name, string fn);
string getName();
double getAverage();
void addScore(int);
};
string CStudent::getName() {
return name;
}
double CStudent::getAverage() {
int av = 0;
for (auto x = scores.begin(); x != scores.end(); x++) {
av += *x;
}
return av / scores.size();
}
void CStudent::addScore(int sc) {
scores.push_back(sc);
}
int main()
{
CStudent stud1;
cout<< stud1.getName()<< endl;

return 0;
}