左移位运算符重载

0 c++ operator-keyword

大家好,

我正在尝试重载左移位运算符<<,以执行以下操作:

char value[] = "Hello";
value << 2;
Run Code Online (Sandbox Code Playgroud)

这样做时,我希望将其打印为:“val”,以便删除最后两个字符;我的问题是我无法正确声明我的重载函数。

我的代码是:

//the .h file    
#pragma once
#include <iostream>

class Operators
{
public:
    char *word;
    int number;

    Operators(void);
    Operators(char str[], int num);
    ~Operators(void);
    void Print(void);
    friend char & operator<<(char &stream, int &nr);     
};

#include "StdAfx.h"
#include "Operators.h"
#include <iostream>

Operators::Operators(void)
{
    word = "";
    number = 0;
}

Operators::Operators(char *str, int num)
{
    word = str;
    number = num;
}

Operators::~Operators(void)
{
}

void Operators::Print(void)
{
    printf("\nThe String: %s", word);
}

friend char & operator<<(char &stream, int &nr)
{

    return stream;
}

// Operator_Overloading.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Operators.h"
#include <conio.h>
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    char value[] = "Hello";
    Operators op(value, 2);


    op.Print();

    _getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 5

如果任何运算符不涉及至少一种用户定义的类型,则不能重载它们。您的用例涉及 achar[N]和 an int,即您不能为这些参数重载任何运算符。