我尝试重载operator<<,但有警告我无法重载。我可以按如下方式重载该运算符:
std::cout << test4 << std::endl;
Run Code Online (Sandbox Code Playgroud)
但是我不能按如下方式重载它:
std::cout << test2 + test3 << std::endl;
Run Code Online (Sandbox Code Playgroud)
我的主要代码是:
Stonewt test2(2, 8, Stonewt::STONE);
std::cout << "test2: " << test2 << std::endl;
Stonewt test3(2, 3, Stonewt::POUNDS);
std::cout << "test3: " << test3 << std::endl;
Stonewt test4 = test2 + test3;
std::cout << test4 << std::endl; // operator << can overload
std::cout << test2 + test3 << std::endl; // operator << cannot overload
Run Code Online (Sandbox Code Playgroud)
下面是friend功能
std::ostream& operator <<(std::ostream& os, Stonewt& a)
{
if …Run Code Online (Sandbox Code Playgroud)