【问题标题】:friend function not printing out what it should朋友功能没有打印出它应该打印的内容
【发布时间】:2017-03-28 04:21:50
【问题描述】:

每当我运行程序时,都没有输出,程序就结束了。难道我做错了什么?我确定我错过了一些东西,但我似乎无法弄清楚。

#include <iostream>
#include <string>

using namespace std;

class Addr
{
public:
    Addr(int i = 0){
        total = i;
    }

void addNum(int num){
    total += num;
}

int getNum(){ 
    return total; }

friend int print(Addr& var);

private:
   int total;
};

int print(Addr& var){
    return var.total;
}

int main()
{
    Addr object1;
    object1.addNum(3);
    print(object1);

    return 0;
 }

【问题讨论】:

  • 如果您希望打印某些内容,您应该使用cout,例如:cout&lt;&lt;print(object1);。您的代码运行正常。

标签: c++ oop friend friend-function


【解决方案1】:

您的程序运行正常。没有输出,因为您没有在程序的控制台中打印任何内容。

print 函数仅返回 total。

如果您希望将值打印到控制台,那么您可以例如更改定义如下:

int print(Addr& var){
    cout << var.total << endl; // this prints to the console output
    return var.total;
}

【讨论】:

    【解决方案2】:

    您的代码没有问题。事实是没有使用打印功能。我修改了你的 main 函数。

    int main()
    {
        Addr object1;
        object1.addNum(3);
    
        cout<<print(object1);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2016-01-17
      • 2016-04-07
      • 2015-05-23
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多