1

在我的头文件中:

Esame();
Esame(string);
Esame(string, Voto);

这是一个 C++ 测试器类:

//OK
Esame esame("Algoritmi e strutture dati", 30);
esame.stampaEsame();

//OK
Esame esame2("Metodi Avanzati di Programmazione");
esame2.setVoto(26);
esame2.stampaEsame();

//ERROR 
Esame esame3();
esame3.setVoto(26); //Method could not be resolved
esame3.stampaEsame(); //Method could not be resolved

代码根本无法编译。如果在上面的代码中使用相同的类创建了对象,为什么找不到方法?

4

2 回答 2

3

esame3() does'nt call a default constructor. In your case the compiler is thinking that you have declared a method

It should be

Esame esame3;

OR

Esame esame3=Esame();

Using new to create an object would create an object that would be allocated dynamically..

In that case your class would have to be a pointer like this

Esame *esame3=new Esame;

You would have to use -> instead of . to access member method or variables..

esame3->method1();
esame3->varable1;
于 2012-10-21T17:21:38.833 回答
1

Esame esame3();是一个函数声明。esame3在这种情况下不命名对象。它声明了一个被调用的函数,该函数esame3不带参数并返回一个类型为 的对象Esame

这被称为最令人头疼的解析

要使用默认构造函数创建对象,请使用Esame esame3;(无括号):

Esame esame3;
esame3.setVoto(26); 
esame3.stampaEsame();
于 2012-10-21T17:18:52.440 回答