相关疑难解决方法(0)

运算符重载的基本规则和习惯用法是什么?

注意:答案是按照特定的顺序给出的,但由于许多用户根据投票而不是给出的时间对答案进行排序,因此这里是答案索引,它们是最有意义的顺序:

(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)

c++ operator-overloading operators c++-faq

2074
推荐指数
8
解决办法
88万
查看次数

错误:重载'operator <<'必须是二元运算符(有3个参数)

我知道有很多这样的问题,但我找不到适合我的解决方案.

我试图制作简单的分数计算器,而不是可以添加或减去任意数量的函数,并将答案写为减少的分数.

示例:input = 3/2 + 4/8,output = 2

我正在尝试重载运算符以实现此目的.

所以在程序中,我正在尝试开发输入,其中包含由运算符'+'或' - '分隔的分数表达式.

表达式中的分数数是任意的.

以下6行中的每一行都是有效输入表达式的示例:

1/2 + 3/4
1/2 -5/7+3/5
355/113
3    /9-21/    -7
4/7-5/-8
-2/-3+7/5
Run Code Online (Sandbox Code Playgroud)

*我遇到的问题是,当我运行程序时,它有一个过载操作错误:错误:重载'operator <<'必须是二元运算符(有3个参数)*

  /Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:61:22: error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
  ostream& Fraction::operator<<(ostream &os, Fraction& n)
                     ^
/Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:80:22: error: overloaded 'operator>>' must be a binary operator (has 3 parameters)
  istream& Fraction::operator>>(istream &os, Fraction& n)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这是一个错误.

我的以下代码如下:

CPP文件

#include "Fraction.h"

Fraction::Fraction(int a, int b)
{

}
int Fraction::find_gcd (int n1, int …
Run Code Online (Sandbox Code Playgroud)

c++ overloading operator-overloading

25
推荐指数
1
解决办法
4万
查看次数

警告定义在命名空间内声明的友元运算符

有人可以向我解释来自 g++ 的警告吗?

鉴于以下代码

#include <iostream>

namespace foo
 {
   struct bar
    { friend std::ostream & operator<< (std::ostream &, bar const &); };
 }

std::ostream & foo::operator<< (std::ostream & o, foo::bar const &)
 { return o; }

int main ()
 {
   foo::bar  fb;

   std::cout << fb;
 }
Run Code Online (Sandbox Code Playgroud)

我得到(来自 g++ (6.3.0) 但不是来自 clang++ (3.8.1) 而不是(感谢 Robert.M)来自 Visual Studio(2017 社区))这个警告

tmp_002-11,14,gcc,clang.cpp:10:16: warning: ‘std::ostream& foo::operator<<(std::ostream&, const foo::bar&)’ has not been declared within foo
 std::ostream & foo::operator<< (std::ostream & o, foo::bar const &)
                ^~~
tmp_002-11,14,gcc,clang.cpp:7:29: …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces g++ operator-overloading friend

7
推荐指数
2
解决办法
2280
查看次数

operator <<重载ostream

为了使用cout:std :: cout << myObject,为什么我必须传递一个ostream对象?我认为这是一个隐含的参数.

ostream &operator<<(ostream &out, const myClass &o) {

    out << o.fname << " " << o.lname;
    return out;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

c++ overloading ostream operator-keyword

6
推荐指数
1
解决办法
3577
查看次数

为什么重载ostream的运算符<<需要引用"&"?

我一直在学习C++.

从这个页面,我明白ostream的重载"<<"运算符可以通过这种方式完成.

ostream& operator<<(ostream& out, Objects& obj) {
    //
    return out;
} 
//Implementation
Run Code Online (Sandbox Code Playgroud)

friend ostream& operator<<(ostream& out, Object& obj);
//In the corresponding header file
Run Code Online (Sandbox Code Playgroud)

我的问题是...为什么这个功能需要"和"在结束ostreamObject

至少我知道"&"习惯了......

  1. 取一个值的地址
  2. 声明对类型的引用

但是,我认为它们都不适用于上述的重载.我花了很多时间在Google上搜索和阅读教科书,但我找不到答案.

任何建议将被认真考虑.

c++ operator-overloading

6
推荐指数
1
解决办法
2490
查看次数

如何在模板类中拆分模板友元函数的定义?

下面的示例编译良好,但我无法弄清楚如何在这种特殊情况下分离运算符 <<() 的声明和定义。

每次我尝试拆分定义时,朋友都会造成麻烦,并且 gcc 抱怨运算符 <<() 定义必须恰好采用一个参数。

#include <iostream>
template <typename T>
class Test {
    public:
        Test(const T& value) : value_(value) {}

        template <typename STREAM>
        friend STREAM& operator<<(STREAM& os, const Test<T>& rhs) {
            os << rhs.value_;
            return os;
        }
    private:
        T value_;
};

int main() {
    std::cout << Test<int>(5) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Operator<<() 应该有一个自由的第一个参数来处理不同类型的输出流(std::cout、std::wcout 或 boost::asio::ip::tcp::iostream)。第二个参数应该绑定到周围类的专门版本。

Test<int> x;
some_other_class y;

std::cout << x; // works
boost::asio::ip::tcp::iostream << x; // works

std::cout << y; // doesn't work
boost::asio::ip::tcp::iostream << y; …
Run Code Online (Sandbox Code Playgroud)

c++ templates friend-function

5
推荐指数
1
解决办法
1042
查看次数

C++ toString运算符similair到Object.toString

在Java中,每个Object都有一个toString方法和一个哈希码方法.C++中的每个对象都有等效的哈希码和toString吗?

c++ java tostring

3
推荐指数
1
解决办法
347
查看次数

C++如何遍历对象的std :: vector并在控制台上显示内容

For循环应该遍历std :: vector并填充内容.

First for循环给出了一条错误消息:

没有找到二元运算符<<不可转换

vector<MyClass>classVector;
    for (vector<MyClass>::iterator i = classVector.begin();
                           i != classVector.end();
                           ++i)
            {
                cout << *i << endl;
            }
Run Code Online (Sandbox Code Playgroud)

MyClass.h:

class MyClass{

private:

    string newTodayTaskString;

public:
    MyClass(string t) : newTodayTaskString (t){}

    ~MyClass(){}
};
Run Code Online (Sandbox Code Playgroud)

这个for循环遍历字符串向量并且完美地工作.为什么?

vector<string>stringVector;
   for (vector<string>::iterator i = stringVector.begin(); 
                         i != stringVector.end(); 
                         ++i) 
            {
                cout<<*i<<endl;
            }
Run Code Online (Sandbox Code Playgroud)

c++ stdvector

2
推荐指数
1
解决办法
8450
查看次数

如何在C++中重载索引运算符?

我有以下代码声明一个重载的类operator[],如下所示:

#include <iostream>
#include <vector>

using namespace std;

class BitSet
{
private:
    int size;
public:
    vector<int> set;
    int &operator [] (int index) {
        return set[index];
    }
    BitSet(int nsize = 0)
    {
        cout << "BitSet creating..." << endl;
        size = nsize;
        initSet(size);
    }
    void initSet(int nsize)
    {
        for (int i = 0; i < nsize; i++)
        {
            set.push_back(0);
        }
    }
    void setValue(int key, int value)
    {
        set[key] = value;
    }
    int getValue(int key, int value)
    {
        return set[key];
    } …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading

2
推荐指数
1
解决办法
116
查看次数

C++:运算符重载 - cout和cin - ostream函数,不能被引用 - 它是一个已删除的函数

我重载了一个cout和cin opeartor,当我尝试使用它时,它给了我一个像这样的错误:

1 IntelliSense: function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const     std::basic_ostream<_Elem, _Traits>::_Myt &) 
[with _Elem=char, _Traits=std::char_traits<char>]" 
(declared at line 84 of "C:\Program   Files (x86)\Microsoft Visual Studio 12.0\VC\include\ostream") cannot be referenced -- it is a deleted function    
Run Code Online (Sandbox Code Playgroud)

这是我班级的头文件:

#pragma once
#include <iostream>

class Point2D
{
private:
    int m_X;
    int m_Y;
public:
    Point2D(): m_X(0), m_Y(0)
    {
    }

    Point2D(int x, int y): m_X(x), m_Y(y)
    {
    }

    friend std::ostream& operator<< (std::ostream out, const Point2D &point)
    {
        out << "(" << point.m_X << "," << point.m_Y << ")" …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
1696
查看次数

C++,错误与operator <<不匹配

请指导我.我必须编写一个程序,其中包含一个名为的类VectorCollection,用于存储实例为string类型的向量集合.我收到以下错误

在std :: cout中没有匹配operator <<

当我尝试使用输出矢量 cout << (*it) << endl;

我有点不愿意在论坛上提出完整的作业问题,但为了避免在这里出现混淆.我想我可能完全偏离轨道,所以任何指导都会受到影响.

编写一个包含名为VectorCollection的类的cpp程序,该类将用于存储实例的类型为string的向量集合.编写一个参数构造函数,该构造函数接收一个字符串数组,用于初始化集合中的值.添加函数以向集合添加实例,从集合中删除实例,从集合中删除所有条目并显示整个集合.同时覆盖*运算符,使其返回两个VectorCollection对象的交集.编写一个程序来测试类中所有成员函数和重载运算符.接下来,修改main函数,以便不是为每个Movie对象创建单独的变量,而是使用样本数据创建至少4个Movie对象的数组.循环播放数组并输出四部电影中每部电影的名称,MPAA等级和平均等级.

//movies.h
//******************************************************************************************************
using namespace std;


#ifndef movies_H
#define movies_H

class VectorCollection
{
    //member variables
        string newtitle,newgentre,newmpaa,newrating;
        vector<VectorCollection> movies;

    public:
        //function declarations

        //default constructor
        VectorCollection();

        //overload constructor
        VectorCollection(string,string,string,string);

        //destructor
        ~VectorCollection();

        void settitle(string);
        void setgentre(string);
        void setmpaa(string);
        void setrating(string);
        void display(vector<VectorCollection>);

};

 #endif // MOVIES_H_INCLUDED


//movies.cpp
//******************************************************************************************************
//constructor definition
VectorCollection::VectorCollection()
{

}

//overloaded constructor def
VectorCollection::VectorCollection(string title,string gentre,string mpaa,string rating)
{
    newtitle = title;
    newgentre = gentre; …
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
362
查看次数

使用std :: ostream在每行之前插入文本

我想知道是否可以从std :: ostream继承,并以某种方式覆盖flush(),以便将某些信息(例如行号)添加到每行的开头.然后我想通过rdbuf()将它附加到std :: ofstream(或cout),这样我得到这样的东西:

ofstream fout("file.txt");
myostream os;
os.rdbuf(fout.rdbuf());

os << "this is the first line.\n";
os << "this is the second line.\n";
Run Code Online (Sandbox Code Playgroud)

会把它放到file.txt中

1 this is the first line.
2 this is the second line.
Run Code Online (Sandbox Code Playgroud)

c++ iostream stl

1
推荐指数
1
解决办法
814
查看次数

具有多个属性的预定义运算符

我是C ++的新手,我需要作业方面的帮助。

创建一个Num类,其对象包含一个双精度值。可以将此值输出到流出。为该类重新定义算术运算符“ +”和“-”,以便当一个操作数为int类型时,该对象仅涉及其值的整个部分。例如

  Num x(5.5);
  cout<<"x="<<x<<endl;// return 5.5
  int a=2; double b=2.5;
  cout<<"a+x="<<a+x<<endl;// return 7
  cout<<"x+a="<<x+a<<endl;// return 7
  cout<<"b+x="<<b+x<<endl;// return 8
  cout<<"x+b="<<x+b<<endl;// return 8
Run Code Online (Sandbox Code Playgroud)

那是我的代码:

class Num
{
    double _num;
    public: Num(double n) : _num(n) {};

    double operator+(double b)
    {
        if ( (_num - (int)_num) == 0 ||  (b - (int)b) == 0) {
            return (int)_num + (int)b;
        } else {
            return _num + b;
        }
    }

    double operator-(double b)
    {
        if ( (_num - (int)_num) == 0 || …
Run Code Online (Sandbox Code Playgroud)

c++

-3
推荐指数
1
解决办法
59
查看次数