麻烦使用私有变量与友元函数

时间:2017-10-29 23:21:53

标签: c++

我有一个.h文件

  #ifndef flashdrive_2_0_h
#define flashdrive_2_0_h

namespace cs52 {

    class FlashDrive {

    public:

        FlashDrive( );
        FlashDrive( int capacity, int used, bool pluggedIn );

        void plugIn( );
        void pullOut( );
        void writeData( int amount );
        void eraseData( int amount );
        void formatDrive( );

        int getCapacity( );
        void setCapacity( int amount );

        int getUsed( );
        void setUsed( int amount );

        bool isPluggedIn( );


        friend FlashDrive operator+(const FlashDrive& flsh1, const FlashDrive& flsh2);


    private:

        int my_StorageCapacity;
        int my_StorageUsed;
        bool my_IsPluggedIn;


    };

}

#endif /* flashdrive_2_0_h */

也是.cpp文件

#include <stdio.h>
#include "flashdrive_2_0.h"
#include <iostream>

using namespace cs52;
using namespace std;


cs52::FlashDrive::FlashDrive() {

    int my_StorageCapacity = 0;
    int my_StorageUsed = 0;
    bool my_IsPluggedIn = false;

}

cs52::FlashDrive::FlashDrive( int capacity, int used, bool pluggedIn ){

    int my_StorageCapacity = capacity;
    int my_StorageUsed = used;
    bool my_IsPluggedIn = pluggedIn;

}

    FlashDrive operator+(const FlashDrive& flsh1, const FlashDrive& flsh2){


    new1.my_StorageUsed flsh1.my_StorageUsed + flsh2.my_StorageUsed;


    return new1;
}

和一个main.cpp

#include <iostream>
#include "flashdrive_2_0.h"

using namespace std;
using namespace cs52;

int main( )
{
    cs52::FlashDrive drive1( 10, 0, false );
    cs52::FlashDrive drive2( 20, 0, false );

return 0;
}

我想让操作员超载&#34; +&#34;在FlashDrive类中添加两个int值。我在.cpp文件中使用重载运算符的定义得到了各种错误。我知道构造函数接受三个不同的参数,但我只想添加int值并忽略bool。

我一直在改写
FlashDrive operator+(const FlashDrive& flsh1, const FlashDrive& flsh2){}

它不会编译。我阅读材料但我仍然不理解如何编写定义以允许我访问类中的私有数据。我最接近定义的是

  FlashDrive operator+(const FlashDrive& flsh1, const FlashDrive& flsh2){

    FlashDrive new1;

    new1.my_StorageUsed = flsh1.my_StorageUsed + flsh2.my_StorageUsed;

    return new1;
}

无法访问my_StorageUsed的私有成员函数数据?

0 个答案:

没有答案
相关问题