7

给定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() 代码)中做哪些简单的更改,以通过该拼写错误获得编译错误?

4

2 回答 2

22

这是因为 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.
于 2010-09-23T11:04:41.577 回答
4

在构造函数中添加explicit关键字:

explicit Grades(int ...) ...
于 2010-09-23T11:06:35.410 回答