相关疑难解决方法(0)

为什么C++编译器没有定义operator ==和operator!=?

我非常喜欢让编译器为你做尽可能多的工作.在编写一个简单的类时,编译器可以为"free"提供以下内容:

  • 默认(空)构造函数
  • 复制构造函数
  • 析构函数
  • 赋值运算符(operator=)

但它似乎无法给你任何比较运算符 - 如operator==operator!=.例如:

class foo
{
public:
    std::string str_;
    int n_;
};

foo f1;        // Works
foo f2(f1);    // Works
foo f3;
f3 = f2;       // Works

if (f3 == f2)  // Fails
{ }

if (f3 != f2)  // Fails
{ }
Run Code Online (Sandbox Code Playgroud)

有这么好的理由吗?为什么执行逐个成员比较会成为问题?显然,如果类分配内存然后你要小心,但对于一个简单的类肯定编译器可以为你做这个?

c++ operators

286
推荐指数
11
解决办法
8万
查看次数

在比较C++中的结构时找不到==运算符

比较以下结构的两个实例,我收到一个错误:

struct MyStruct1 {
    Position(const MyStruct2 &_my_struct_2, const int _an_int = -1) :
        my_struct_2(_my_struct_2),
        an_int(_an_int)
    {}

    std::string toString() const;

    MyStruct2 my_struct_2;
    int an_int;
};
Run Code Online (Sandbox Code Playgroud)

错误是:

错误C2678:二进制'==':找不到哪个运算符带有'myproj :: MyStruct1'类型的左手操作数(或者没有可接受的转换)

为什么?

c++ struct comparison-operators

91
推荐指数
4
解决办法
10万
查看次数

迭代C++中的结构

我有一个结构

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;
Run Code Online (Sandbox Code Playgroud)

我想迭代每个结构的每个成员并打印它的值.就像是:

void print_struct_value(struct *A)
{
    for each member of struct A
    cout << "struct name . member name" << "value";
}
Run Code Online (Sandbox Code Playgroud)

如何在C++中完成?

c++ struct

30
推荐指数
5
解决办法
4万
查看次数

标签 统计

c++ ×3

struct ×2

comparison-operators ×1

operators ×1