【发布时间】:2020-04-02 22:30:17
【问题描述】:
我正在尝试编写一个具有 Student 类的 C++ 程序。我正在尝试为name 属性创建一个吸气剂,但我收到了这个错误:
有什么想法吗?
这是我到目前为止所做的:
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
using namespace std;
class Student
{
char *AM;
string name;
int semester, lessons;
float *passed;
public:
Student (const char *am, string n); //Constructor that I give only the serial number (AM) and the name
Student (const char *am, string n, int semester); //Constructor that I give only the serial number (AM), the name and the semester
Student (const char *am, string n, int semester, int lessons, float * passed); //Constructor that I give values to all the attributes
Student (Student &x);
void setAm (const char *am); //Set serial number
char * getAm () const; //Get serial number
void setName (string n); //Set name
string * getName () const; //Get name
};
//Only AM and Name
Student::Student(const char *am, string n)
{
int l = strlen (am);
AM = new char [l + 1];
strcpy (AM, am);
name = n;
semester = 1;
lessons = 0;
*passed = {0};
}
//Only serial number (am), name (n), semester (e)
Student::Student(const char * am, string n, int e)
{
int l = strlen (am);
AM = new char [l + 1];
strcpy (AM, am);
name = n;
semester = e;
lessons = 0;
*passed = {0};
}
//Constructor that we give values to all variables
Student::Student(const char * am, string n, int e, int perasm, float *p)
{
int l = strlen (am), i;
AM = new char [l + 1];
strcpy (AM, am);
name = n;
semester = e;
lessons = perasm;
*passed = *p;
}
void Student::setAm(const char *am)
{
delete [] AM;
int l = strlen(am);
AM = new char[l + 1];
strcpy (AM, am);
}
char * Student::getAm() const
{
return AM;
}
void Student::setName (const string s)
{
name = s;
}
string * Student::getName () const
{
return *name;
//return c;
}
int main()
{
Student Kostas("123", "Kostas");
cout << Kostas.getAm() <<endl;
Kostas.setAm("354");
cout << Kostas.getAm() <<endl;
float p[] = {5.1, 4.4, 0.0, 0.0, 0.0};
Student Giwrgos("678", "Giwrgos", 6, 5, p);
cout << Giwrgos.getName();
return 0;
}
【问题讨论】:
-
你的代码中充满了指针——为什么?
std::string*通常是一个错误的标志。 -
附带说明,
float *passed;永远不会被指定指向任何东西,所以*passed = {0};在运行时会有未定义的行为。
标签: c++ class pointers operator-keyword getter