Stack Overflow教给我的很多东西都是所谓的"最令人烦恼的解析",经典地用一条线来证明
A a(B()); //declares a function
Run Code Online (Sandbox Code Playgroud)
虽然这对于大多数人而言,直观地看起来是a类型对象的声明A,将临时B对象作为构造函数参数,它实际上是一个函数a返回的声明A,将一个指针指向一个返回的函数,它B本身不带参数.同样的线
A a(); //declares a function
Run Code Online (Sandbox Code Playgroud)
也属于同一类别,因为它代替一个对象,它声明了一个函数.现在,在第一种情况下,这个问题的通常解决方法是在其周围添加一组额外的括号/括号B(),因为编译器会将其解释为对象的声明
A a((B())); //declares an object
Run Code Online (Sandbox Code Playgroud)
但是,在第二种情况下,执行相同操作会导致编译错误
A a(()); //compile error
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么?是的我非常清楚正确的"解决方法"是将其更改为A a;,但我很想知道()第一个示例中的额外功能是什么,然后在重新应用它时不起作用第二个例子.A a((B()));变通办法是否是写入标准的特定异常?
我遇到了类的问题,将一个const对象(多态结构)传递给一个显式构造函数,该构造函数对该多态结构的基类进行了const引用.这是示例(这不是我的代码,这里是解释)
class Base
{
...
}
class Derived:public Base
{
...
}
class Problem
{
Problem(const Base&);
...
}
void myFunction(const Problem& problem)
{
...
}
int main()
{
//explicit constructor with non const object
Derived d;
Problem no1(d); //this is working fine
myFunction(no1);
//implicit constructor with const object
Problem no2=Derived(); //this is working fine, debugged and everything called fine
myFunction(no2); //is working fine
//explicit constructor with const object NOT WORKING
Problem no3(Derived()); //debugger jumps over this line (no compiler …Run Code Online (Sandbox Code Playgroud)