为什么下面的程序输出而不是hello
and ?0/1
1
#include <cassert>
#include <iostream>
class Drob
{
private:
int m_numerator;
int m_denominator;
public:
Drob(int numerator=0, int denominator=1) :
m_numerator(numerator), m_denominator(denominator)
{
std::cout << "hello" << std::endl;
assert(denominator != 0);
}
Drob(const Drob &drob) :
m_numerator(drob.m_numerator), m_denominator(drob.m_denominator)
{
std::cout << "Copy constructor worked here!\n";
}
friend std::ostream& operator<<(std::ostream& out, const Drob &d1);
};
std::ostream& operator<<(std::ostream& out, const Drob &d1)
{
out << d1.m_numerator << "/" << d1.m_denominator;
return out;
}
int main()
{
Drob sixSeven (Drob());
std::cout << sixSeven << std::endl;
return 0;
}
如果Drob sixSeven (Drob());
用Drob sixSeven {Drob()};
或 用Drob sixSeven = Drob();
then 替换,结果会是hello
and 0/1
,但是直接初始化的情况下,结果就不同了。
根据大多数令人烦恼的解析
Drob sixSeven (Drob());
是一个函数声明sixSeven
,operator<<(std::ostream& out, const Drob &d1)
甚至没有被调用。直接初始化是
Drob sixSeven{};