C++ 构造函数问题 // 继承的类

C++ Constructor problems // Inherited class

本文关键字:继承 C++ 问题 构造函数      更新时间:2023-10-16

初始问题已解决。(这是一个重新定义错误)

此外,我不知道如何创建一个提供以下内容的学生构造函数:

这就是我希望我的程序/构造函数工作的方式:

//main.cpp
Student s1(4015885);
s1.print();
Student s2("Test", "Student", 22, 5051022);
s2.print();

输出应如下所示:

Standart
Name
18
4015885
Test
Student
22
5051022

s1 有效,但 s2 不起作用,因为我没有合适的构造函数

这是我的人。

#pragma once
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
    Person(string name = "Standard", string surname =  "Name", int age**strong text** = 18);                              
    //GET
    //SET
    void print();
protected:
    string name, surname;
    int age;
};

人.cpp

#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
Person::Person(string n, string s, int a) : name(n), surname(s), age(a)
{
    cout << "Person constructor" << endl;
}
void Person::print() {
    cout << name << endl << surname << endl << age << endl << endl;
}

学生.h

#pragma once
//#ifndef PERSON_H
//#define PERSON_H
#include "Person.h"
class Student : public Person {
public:
    Student(int matrikel_nummer);
    int get_matriculation_number();
    void set_matriculation_number(int matriculation_number) {
        this->matriculation_number = matriculation_number;
    }
    void print();
private:
    int matriculation_number;
};
//#endif

学生.cpp

#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
Student::Student(int matrikel_nummer) : Person(name, surname, age)
{
    cout << "Student constructor" << endl;
    this->matriculation_number = matriculation_number;
}
void Student::print() {
    cout << name << endl
            << surname << endl
            << age << endl 
            << matriculation_number << endl << endl;
}

Student.h你有

Student(int matriculation_number) : Person(name, surname, age){};

它声明并定义了Student的构造函数。 那么在Student.cpp你有

Student::Student(int matrikel_nummer) : Person(vorname, nachname, alter)
{
    cout << "Student constructor" << endl;
    this->matrikel_nummer = matrikel_nummer;
}

这重新定义了相同的构造函数。

你要么需要摆脱类中的构造函数定义

Student(int matriculation_number) : Person(name, surname, age){};
//becomes
Student(int matriculation_number);

或者删除 cpp 文件中的构造函数。

此外,name, surname, age, vorname, nachname, alter不会出现在您提供的代码中的任何位置。 除非他们在其他地方声明,否则这不会编译。

编辑:

从注释来看,您的Student构造函数应该是

Student(string n, string s, int a, int mn) : Person(n, s, a), matriculation_number(mn) {}

你可以把它放在标题中,你不需要在 cpp 文件中定义构造函数。

你的错误在这里:

Student(int matriculation_number) : Person(name, surname, age){};

删除{}和基本 ctor 调用:

Student(int matriculation_number);

您已经定义了 student 的构造函数主体:

Student(int matriculation_number) : Person(name, surname, age){};

这已经是构造函数体的完整实现,您应该将其写在标头中:

Student(int matriculation_number);