gpt4 book ai didi

c++ - 如何在意外构建时出现编译错误?

转载 作者:可可西里 更新时间:2023-11-01 18:04:12 25 4
gpt4 key购买 nike

给定 2 个类:

...
class Grades{
public:
Grades(int numExams) : _numExams(numExams){
_grdArr = new double[numExams];
}
double GetAverage() const;
...
private: // The only data members of the class
int _numExams;
double *_grdArr;
};

class Student{
public:
Student(Grades g) : _g(g){
}
...
private: // The only data members of the class
Grades _g;
};
...

还有一个简短的主程序:

int main(){
int n = 5; // number of students
Grades g(3); // Initial grade for all students
// ... Initialization of g – assume that it's correct
Student **s = new Student*[n]; // Assume allocation succeeded
for (int it = 0 ; it < n ; ++it){
Grades tempG = g;
// ... Some modification of tempG – assume that it's correct
s[it] = new Student(tempG);
}
// ...
return 0;
}

这段代码工作正常。但是由于打字错误,该行:

Grades tempG = g;

已更改为:

Grades tempG = n;

仍然通过了编译。我可以在代码(main() 代码)中做哪些简单的更改以因该拼写错误而导致编译错误?

最佳答案

这是因为 Grades 有一个单参数构造函数,它充当转换构造函数。这样的构造函数接受一个 int 参数并创建一个 Grades 类型的对象。

因此编译成功。

使'Grades'的构造函数显式

explicit Grades(int numExams);

这将不允许

Grades g = 2;

但允许以下所有内容

Grades g = Grades(2)  // direct initialization

Grades g = (Grades)2; // cast

Grades g = static_cast<Grades>(2);

Grades g(2); // direct initialization.

关于c++ - 如何在意外构建时出现编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com