【发布时间】:2015-06-21 07:00:46
【问题描述】:
#include <iostream>
class dummy{
public:
constexpr
dummy(int one, int two) noexcept
:x(one),y(two){
}
constexpr int getX() noexcept{
return x;
}
constexpr int gety() noexcept{
return y;
}
constexpr int operator+(const dummy& asd){
return (this->getX() + asd.getX() + this->gety() + asd.gety()) ;
}
private:
int x;
int y;
};
int main(){
constexpr dummy d1(2,4);
constexpr dummy d2(2,4);
int rand = 10;
std::cout<<d1+d2<<std::endl;
return 0;
}
据我了解,如果函数声明为 constexpr 并且采用 constexpr 值,则可以在编译时对其进行评估。
问题:
从这一行开始,std::cout<<d1+d2<<std::endl; 因为d1 + d2 是一个 constexpr 而 cout 运算符不是。 d1+d2 会在编译时进行评估吗?周围的cout 会发生什么?我很担心里面发生了什么。
【问题讨论】:
-
输出结果基本上等价于
std::cout << 12 << std::endl;d1+d2的值可以在编译时计算出来,但当然字符'1'和'2'只能写入标准输出运行时。