左移位运算符重载

时间:2013-09-16 09:31:19

标签: c++ operator-keyword

大家好,

我试图重置左移位操作符<<,以执行以下操作:

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;
}

1 个答案:

答案 0 :(得分:4)

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