[英]Left shift bit operator overloading
大家好,
我試圖重載左移位運算符<<
,以執行類似的操作:
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
,即,您不能為這些參數重載任何運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.