左移位运算符重载

Left shift bit operator overloading

本文关键字:重载 运算符 左移      更新时间:2023-10-16

大家好,

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

char value[] = "Hello";
value << 2;

这样做时,我希望将其打印为:"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;
}

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