小编YiL*_*Luo的帖子

如何在ruby中设置比较元素?

我试图将自定义对象放在一个集合中.我试过这个:

require 'set'

class Person
  include Comparable

  def initialize(name, age)
    @name = name
    @age = age
  end
  attr_accessor :name, :age

  def ==(other)
    @name == other.name
  end
  alias eql? ==
end

a = Person.new("a", 18)
b = Person.new("a", 18)
people = Set[]
people << a
people << b

puts a == b # true
Run Code Online (Sandbox Code Playgroud)

似乎Set没有使用Object#eql?==方法识别相同的对象:

puts people # #<Set: {#<Person:0x00007f9e09843df8 @name="a", @age=18>, #<Person:0x00007f9e09843da8 @name="a", @age=18>}>
Run Code Online (Sandbox Code Playgroud)

如何Set识别两个相同的对象?

ruby set

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

在 C++ 中为全局变量赋值

我想知道为什么给全局变量赋值会导致错误

#include <iostream>

using namespace std;

int x = 5;
x = 3; // error: C++ requires a type specifier for all declarations
Run Code Online (Sandbox Code Playgroud)

我不是刚刚在上面的行中声明了吗?好吧,让我们看看 x 是否存在;

#include <iostream>

using namespace std;

int x = 5;
x = 3; // error: C++ requires a type specifier for all declarations
Run Code Online (Sandbox Code Playgroud)

好的,所以它确实同意 x 已定义,但类型“还不是”int。有人可以解释这种行为吗,你怎么称呼这种行为?它是怎么发生的?为什么这样设计?

c++ programming-languages

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

标签 统计

c++ ×1

programming-languages ×1

ruby ×1

set ×1