意外构建时如何得到编译错误?
给定 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() 代码)中做哪些简单的更改来通过该拼写错误获得编译错误?
Given 2 classes:
...
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;
};
...
And, a short main program:
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;
}
This code works fine.
But by typo mistake the line:
Grades tempG = g;
has changed to:
Grades tempG = n;
and still it passes the compilation.
What simple change can i do in the code (the main() code) to get a compilation error by that typo mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为 Grades 有一个单参数构造函数,充当转换构造函数。这样的构造函数接受一个 int 参数并创建一个 Grades 类型的对象。
因此编译成功。
明确“Grades”的构造函数
这将不允许
但允许以下所有内容
This is because Grades has a single argument constructor which acts as a converting constructor. Such a constructor takes an int argument and creates an object of type Grades.
Therefore the compilation is successful.
Make the consructor of 'Grades' explicit
This will disallow
but allows all of the following
将
explicit
关键字添加到构造函数中:Add the
explicit
keyword to the constructor: