【问题标题】:Regarding default constructor an object initialization/usage in C++ OOP关于默认构造函数,C++ OOP 中的对象初始化/使用
【发布时间】:2018-12-08 11:54:07
【问题描述】:

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

【问题讨论】:

  • 请始终包含错误消息。
  • 声明了一个构造函数,你需要定义它,或者让编译器使用= default为你定义它。
  • 如果您将CStudent(); 更改为CStudent() = default;,您甚至可以强制编译器为您实现构造函数。 CStudent() { } 也可以。在这两种情况下,编译器都会为所有成员使用默认构造函数。
  • @Scheff 它实际上会使用 name 的默认成员初始化器;)
  • 题外话:在这样的全局范围内你应该避免using namespace std;,见stackoverflow.com/questions/1452721/…

标签: c++ oop object constructor initialization


【解决方案1】:

这应该可以工作,正如 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;
}

【讨论】:

    【解决方案2】:

    当你在课堂上写作时:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2012-01-02
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2014-07-25
      • 2021-05-28
      • 2011-06-12
      相关资源
      最近更新 更多